Use PHP functions in JavaScript

JavaScript substr_replace

Replaces part of a string with another string

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
function substr_replace (str, replace, start, length) {
    // Replaces part of a string with another string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/substr_replace    // +   original by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0);
    // *     returns 1: 'bob'
    // *     example 2: $var = 'ABCDEFGH:/MNRPQR/';
    // *     example 2: substr_replace($var, 'bob', 0, $var.length);    // *     returns 2: 'bob'
    // *     example 3: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0, 0);
    // *     returns 3: 'bobABCDEFGH:/MNRPQR/'
    // *     example 4: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 10, -1);
    // *     returns 4: 'ABCDEFGH:/bob/'    // *     example 5: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', -7, -1);
    // *     returns 5: 'ABCDEFGH:/bob/'
    // *     example 6: 'substr_replace('ABCDEFGH:/MNRPQR/', '', 10, -1)'
    // *     returns 6: 'ABCDEFGH://'
    if (start < 0) { // start position in str        start = start + str.length;
    }
    length = length !== undefined ? length : str.length;
    if (length < 0) {
        length = length + str.length - start;    }
    return str.slice(0, start)+replace.substr(0, length)+replace.slice(length)+str.slice(start+length);
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0);

Should return

1
'bob'

» Example 2

Running

1
2
$var = 'ABCDEFGH:/MNRPQR/';
substr_replace($var, 'bob', 0, $var.length);

Should return

1
'bob'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have substr_replace goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

No comments yet. Be the first!


Contribute a New function