Fork me on GitHub

Learn how to do it in JavaScript. Explore boundaries porting languages. Enjoy functions that turn out to be useful.

Here’s what a JavaScript equivalent for PHP’s str_replace looks like.

function str_replace (search, replace, subject, count) {
  //  discuss at: http://phpjs.org/functions/str_replace/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Gabriel Paderni
  // improved by: Philip Peterson
  // improved by: Simon Willison (http://simonwillison.net)
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Onno Marsman
  // 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://kevin.vanzonneveld.net)
  // bugfixed by: Oleg Eremeev
  // bugfixed by: Glen Arason (http://CanadianDomainRegistry.ca)
  // bugfixed by: Glen Arason (http://CanadianDomainRegistry.ca)
  //    input by: Onno Marsman
  //    input by: Brett Zamir (http://brett-zamir.me)
  //    input by: Oleg Eremeev
  //        note: The count parameter must be passed as a string in order
  //        note: to find a global variable in which the result will be given
  //   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: str_replace(['A','D'], ['x','y'] , 'ASDFASDF' , 'cnt');
  //   returns 4: 'xSyFxSyF' // cnt = 0 (incorrect before fix)
  //   returns 4: 'xSyFxSyF' // cnt = 4 (correct after fix)

  var i = 0,
    j = 0,
    temp = '',
    repl = '',
    sl = 0,
    fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = Object.prototype.toString.call(r) === '[object Array]',
    sa = Object.prototype.toString.call(s) === '[object Array]'
  s = [].concat(s)

  if (typeof (search) === 'object' && typeof (replace) === 'string') {
    temp = replace
    replace = new Array()
    for (i = 0; i < search.length; i += 1) {
      replace[i] = temp
    }
    temp = ''
    r = [].concat(replace)
    ra = Object.prototype.toString.call(r) === '[object Array]'
  }

  if (count) {
    this.window[count] = 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 (count) {
        this.window[count] += ((temp.split(f[j]))
          .length - 1)
      }
    }
  }
  return sa ? s : s[0]
}
View on GitHub Edit on GitHub Source on GitHub

A community initiative

php.js offers community built functions and goes by the McDonald’s Theory. We’ll put online functions that aren't perfect, in the hopes to spark better contributions. Do you have one? You can directly edit this file on GitHub, this will create a Pull Request that the core team can review, and merge into our codebase.

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

Notes

The count parameter must be passed as a string in order to find a global variable in which the result will be given

Example 1

str_replace(' ', '.', 'Kevin van Zonneveld');
Should return:
'Kevin.van.Zonneveld'

Example 2

str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
Should return:
'hemmo, mars'

Example 3

str_replace(Array('S','F'),'x','ASDFASDF');
Should return:
'AxDxAxDx'

Example 4

str_replace(['A','D'], ['x','y'] , 'ASDFASDF' , 'cnt');
Should return:
'xSyFxSyF' // cnt = 0 (incorrect before fix)
'xSyFxSyF' // cnt = 4 (correct after fix)

« More strings functions