PHP's str_replace in JavaScript

Here’s what our current JavaScript equivalent to PHP's str_replace looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
module.exports = function str_replace (search, replace, subject, countObj) { // eslint-disable-line camelcase
// discuss at: http://locutus.io/php/str_replace/
// original by: Kevin van Zonneveld (http://kvz.io)
// improved by: Gabriel Paderni
// improved by: Philip Peterson
// improved by: Simon Willison (http://simonwillison.net)
// improved by: Kevin van Zonneveld (http://kvz.io)
// improved by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (http://brett-zamir.me)
// revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// bugfixed by: Anton Ongson
// bugfixed by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Oleg Eremeev
// bugfixed by: Glen Arason (http://CanadianDomainRegistry.ca)
// bugfixed by: Glen Arason (http://CanadianDomainRegistry.ca)
// input by: Onno Marsman (https://twitter.com/onnomarsman)
// input by: Brett Zamir (http://brett-zamir.me)
// input by: Oleg Eremeev
// note 1: The countObj parameter (optional) if used must be passed in as a
// note 1: object. The count will then be written by reference into it's `value` property
// example 1: str_replace(' ', '.', 'Kevin van Zonneveld')
// returns 1: 'Kevin.van.Zonneveld'
// example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars')
// returns 2: 'hemmo, mars'
// example 3: str_replace(Array('S','F'),'x','ASDFASDF')
// returns 3: 'AxDxAxDx'
// example 4: var countObj = {}
// example 4: str_replace(['A','D'], ['x','y'] , 'ASDFASDF' , countObj)
// example 4: var $result = countObj.value
// returns 4: 4
var i = 0
var j = 0
var temp = ''
var repl = ''
var sl = 0
var fl = 0
var f = [].concat(search)
var r = [].concat(replace)
var s = subject
var ra = Object.prototype.toString.call(r) === '[object Array]'
var sa = Object.prototype.toString.call(s) === '[object Array]'
s = [].concat(s)
var $global = (typeof window !== 'undefined' ? window : global)
$global.$locutus = $global.$locutus || {}
var $locutus = $global.$locutus
$locutus.php = $locutus.php || {}
if (typeof (search) === 'object' && typeof (replace) === 'string') {
temp = replace
replace = []
for (i = 0; i < search.length; i += 1) {
replace[i] = temp
}
temp = ''
r = [].concat(replace)
ra = Object.prototype.toString.call(r) === '[object Array]'
}
if (typeof countObj !== 'undefined') {
countObj.value = 0
}
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + ''
repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]
s[i] = (temp).split(f[j]).join(repl)
if (typeof countObj !== 'undefined') {
countObj.value += ((temp.split(f[j])).length - 1)
}
}
}
return sa ? s : s[0]
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/strings/str_replace'). You could also require the strings module in full so that you could access strings.str_replace instead.

If you intend to target the browser, you can then use a module bundler such as Browserify, webpack or rollup.js.

ES5/ES6

This function targets ES5, but as of Locutus 2.0.2 we also support ES6 functions. Locutus transpiles to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Notes

  • The countObj parameter (optional) if used must be passed in as a object. The count will then be written by reference into it’s value property

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1str_replace(' ', '.', 'Kevin van Zonneveld')'Kevin.van.Zonneveld'
2str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars')'hemmo, mars'
3str_replace(Array('S','F'),'x','ASDFASDF')'AxDxAxDx'
4var countObj = {} str_replace(['A','D'], ['x','y'] , 'ASDFASDF' , countObj) var $result = countObj.value4

« More PHP strings functions