Design & Download
Your JS Library
in Seconds!!!

Snippet: replace() - String Replacement

Written by Christopher West (cwest) on November 16, 2015.
Replace 1 occurrence or as many occurrences as you like of a substring.
function replace(original, target, replacement, opt_maxReplacements) {
  var isRegExp = typeOf(target, 'RegExp');
  var isFn = typeOf(replacement, 'Function');
  return original.replace(
    new RegExp(
      isRegExp ? target.source : quoteRegExp(target),
      isRegExp ? (target + '').replace(/[\s\S]+\/(\w*?)g?(\w*)/, '$1$2g') : 'g'
    function(m) {
      return !(opt_maxReplacements-- <= 0) ? isFn ? replacement.apply(this, arguments) : replacement : m;

The native string replacement function gives us the ability to replace one or all occurrences of a substring matching a RegExp but it doesn't give us the ability to replace all occurrences of a specified string. For this reason YourJS.replace(...) was created.

replace(...) API Documentation


  1. original {string}:
    The string to be modified.
  2. target {RegExp|string}:
    The substring to be found in original and replaced with replacement.
  3. replacement {Function|string}:
    If a function is passed in, it will be called and the return value will be the string replacing the occurrence(s) of target. The first argument will be the matched substring, the penultimate argument will the index within original where the substring was found and the last argument will be a copy an unaltered original. If target is a RegExp with parenthesized submatches those matches will also be passed in after the first argument but before the index and the copy of original. If this is a string, this will be the string replacing the occurrence(s) of target.
  4. opt_maxReplacements {number}:
    Optional. Defaults to Infinity. The maximum number of times target will be replaced.


Returns a modified copy of original with instances target replaced by replacement.