phpjs
Version:
96 lines (80 loc) • 3.04 kB
Markdown
layout: page
title: "JavaScript substr_replace function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/substr_replace:819
- /functions/view/substr_replace
- /functions/view/819
- /functions/substr_replace:819
- /functions/819
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's substr_replace
{% codeblock strings/substr_replace.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/substr_replace.js raw on github %}
function substr_replace (str, replace, start, length) {
// From: http://phpjs.org/functions
// + 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);
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/substr_replace.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/substr_replace.js)
### Example 1
This code
{% codeblock lang:js example %}
substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
'bob'
{% endcodeblock %}
### Example 2
This code
{% codeblock lang:js example %}
$var = 'ABCDEFGH:/MNRPQR/';
substr_replace($var, 'bob', 0, $var.length);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
'bob'
{% endcodeblock %}
### Example 3
This code
{% codeblock lang:js example %}
substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0, 0);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
'bobABCDEFGH:/MNRPQR/'
{% endcodeblock %}
### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}