By Click Upvote


2009-07-17 17:53:46 8 Comments

I have this string:

"Test abc test test abc test test test abc test test abc"

Doing:

str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above.

How can I replace all occurrences of it?

30 comments

@Ws Memon 2019-11-22 11:19:18

check this i'm sure it will hepls you:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = 'Is this "3" dris "3"?';
  var allvar= '"3"';
  var patt1 = new RegExp( allvar, 'g' );
  document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>

Here is the jsfiddle link

@Thomas Orlita 2019-11-11 07:25:36

Currently there is a Stage 3 proposal to ECMAScript that adds the replaceAll method to String.

The usage is the same as the replace method:

String.prototype.replaceAll(searchValue, replaceValue)

Here's an example usage:

'Test abc test test abc test.'.replaceAll('abc', 'foo'); // -> 'Test foo test test foo test.'

(as of 2019) It is not yet included in ECMAScript, but there exist polyfills:

It is supported in the V8 engine behind an experimental flag --harmony-string-replaceall.
Read more on the V8 website.

@CertainPerformance 2019-10-18 02:48:27

There is now a proposal for integrating String.prototype.replaceAll into the official specification. Eventually, developers will not have to come up with their own implementations for replaceAll - instead, modern Javascript engines will support it natively.

The proposal is at stage 3, which means that specification managers have high confidence that it will be integrated into the standard, and:

The solution is complete and no further work is possible without implementation experience, significant usage and external feedback.

There's a good chance we'll start seeing it land in V8 and other browsers soon-ish.

Here are the implementation details:

Per the current TC39 consensus, String.prototype.replaceAll behaves identically to String.prototype.replace in all cases, except for the following two cases:

  1. If searchValue is a string, String.prototype.replace only replaces a single occurrence of the searchValue, whereas String.prototype.replaceAll replaces all occurrences of the searchValue (as if .split(searchValue).join(replaceValue) or a global & properly-escaped regular expression had been used).
  2. If searchValue is a non-global regular expression, String.prototype.replace replaces a single match, whereas String.prototype.replaceAll throws an exception. This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").

Notably, String.prototype.replaceAll behaves just like String.prototype.replace if searchValue is a global regular expression.

You can see a spec-compliant polyfill here.

@Alireza 2017-06-06 13:39:22

Using RegExp in JavaScript could do the job for you, just simply do something like below code, don't forget the /g after which standout for global:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');

If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function, but again if you heavily use this, you can write something like this:

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};

and simply use it in your code over and over like below:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance, only caching the function may effect some faster performance on long strings and also a good practice of DRY code if you want to reuse.

@Rakib Uddin 2019-10-04 15:14:06

str = "Test abc test test abc test test test abc test test abc"

str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')

@Stefan Steiger 2019-07-11 12:45:37

You can do it without Regex, but you need to be careful if the replacement text contains the search text.

e.g.

replaceAll("nihIaohi", "hI", "hIcIaO", true)

So here is a proper variant of replaceAll, including string-prototype:

function replaceAll(str, find, newToken, ignoreCase)
{
    let i = -1;

    if (!str)
    {
        // Instead of throwing, act as COALESCE if find == null/empty and str == null
        if ((str == null) && (find == null))
            return newToken;

        return str;
    }

    if (!find) // sanity check 
        return str;

    ignoreCase = ignoreCase || false;
    find = ignoreCase ? find.toLowerCase() : find;

    while ((
        i = (ignoreCase ? str.toLowerCase() : str).indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    } // Whend 

    return str;
}

Or, if you want to have a string-prototype function:

String.prototype.replaceAll = function (find, replace) {
    let str = this;

    let i = -1;

    if (!str)
    {
        // Instead of throwing, act as COALESCE if find == null/empty and str == null
        if ((str == null) && (find == null))
            return newToken;

        return str;
    }

    if (!find) // sanity check 
        return str;

    ignoreCase = ignoreCase || false;
    find = ignoreCase ? find.toLowerCase() : find;

    while ((
        i = (ignoreCase ? str.toLowerCase() : str).indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    } // Whend 

    return str;
};

@Raghavendra S 2019-05-30 04:43:39

Check this answer may it will help and I used in my project.

function replaceAll(searchString, replaceString, str) {
   return str.split(searchString).join(replaceString);
}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test  test test  test test test  test test "

@Indrajeet Singh 2019-05-29 11:11:11

For replacing a single time use:

var res = str.replace('abc', "");

For replacing multiple times use:

var res = str.replace(/abc/g, "");

@Phan Van Linh 2019-09-30 03:55:23

for someone need to replace \n, you can do it like: replace(/\n/g, '<br/>')

@Nouman Dilshad 2019-05-20 09:18:25

All the answers are accepted, you can do this by many ways. One of the trick to do this is this.

const str = "Test abc test test abc test test test abc test test abc";

const compare = "abc";
arrayStr = str.split(" ");
arrayStr.forEach((element, index) => {
  if (element == compare) {
    arrayStr.splice(index, 1);
  }
});
const newString = arrayStr.join(" ");
console.log(newString);

@sajadre 2019-05-14 18:42:20

The simplest way to this without using any regex is split and join like code here :

var str="Test abc test test abc test test test abc test test abc";
str.split('abc').join('')

@Jessie Lesbian 2019-05-09 05:11:44

This should work.

String.prototype.replaceAll = function (search, replacement){
var str1 = this.replace(search, replacement);
var str2 = this;
while(str1 != str2){
str2 = str1;
str1 = str1.replace(search, replacement);
}
return str1;
}

Example:

Console.log("Steve is the best character in minecraft".replaceAll("Steve" ,"Alex"));

@VhsPiceros 2019-04-16 00:37:43

I use split and join or this funcion

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
      text = text.toString().replace(busca,reemplaza);
  return text;
}

@Adnan Toky 2019-03-25 09:38:38

These are the most common and readable methods.

var str = "Test abc test test abc test test test abc test test abc"

Method-01:

str = str.replace(/abc/g, "replaced text");

Method-02:

str = str.split("abc").join("replaced text");

Method-03:

str = str.replace(new RegExp("abc", "g"), "replaced text");

Method-04:

while(str.includes("abc")){
    str = str.replace("abc", "replaced text");
}

Output:

console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text

@Rinold 2019-02-26 17:36:52

 var myName = 'r//i//n//o//l////d';
  var myValidName = myName.replace(new RegExp('\//', 'g'), ''); > // rinold
  console.log(myValidName);

var myPetName = 'manidog';
var renameManiToJack = myPetName.replace(new RegExp('mani', 'g'), 'jack'); > // jackdog

@prime 2019-02-15 19:15:19

This can be achieved using Regex. Few combinations that might help someone,

var word = "this,\\ .is*a*test,    '.and? / only /     'a \ test?";
var stri = "This      is    a test         and only a        test";

To replace all non alpha characters,

console.log(word.replace(/([^a-z])/g,' ').replace(/ +/g, ' ')); 
Result: [this is a test and only a test]

To replace multiple continuous spaces with one space,

console.log(stri.replace(/  +/g,' ')); 
Result: [This is a test and only a test]

To replace all * characters,

console.log(word.replace(/\*/g,'')); 
Result: [this,\ .isatest,    '.and? / only /     'a  test?]

To replace question marks (?)

console.log(word.replace(/\?/g,'#')); 
Result: [this,\ .is*a*test,    '.and# / only /     'a  test#]

To replace quotation marks,

console.log(word.replace(/'/g,'#'));  
Result: [this,\ .is*a*test,    #.and? / only /     #a  test?]

To replace all ' characters,

console.log(word.replace(/,/g,'')); 
Result: [this\ .is*a*test    '.and? / only /     'a  test?]

To replace a specific word,

console.log(word.replace(/test/g,'')); 
Result: [this,\ .is*a*,    '.and? / only /     'a  ?]

To replace back-slash,

console.log(word.replace(/\\/g,''));  
Result: [this, .is*a*test,    '.and? / only /     'a  test?]

To replace forward slash,

console.log(word.replace(/\//g,''));  
Result: [this,\ .is*a*test,    '.and?  only      'a  test?]

To replace all spaces,

console.log(word.replace(/ /g,'#'));  
Result: [this,\#.is*a*test,####'.and?#/#only#/#####'a##test?]

To replace dots,

console.log(word.replace(/\./g,'#')); 
Result: [this,\ #is*a*test,    '#and? / only /     'a  test?]

@Brijesh Kumar 2019-02-09 08:28:26

Simplest Solution -

let str = "Test abc test test abc test test test abc test test abc";

str = str.split(" ");
str = str.filter((ele, key)=> ele!=="abc")
str = str.join(" ")

Or Simply - 

str = str.split(" ").filter((ele, key) => ele != "abc").join(" ")

@Yash 2019-02-07 13:49:05

Best solution, in order to replace any Character we use these indexOf(), includes(), substring() functions to replace matched String with the provided String in the Current String.

  • String.indexOf() function is to find the nth match index position.
  • String.includes() method determines whether one string may be found within another string, returning true or false as appropriate.
  • String.substring() function is to get the parts of String(preceding,exceding). Added the replace String inbetween these parts to generate final return String.

Following function allows to use any Character.
where as RegExp will not allow some special Character like ** and some Character need to be escape like $.

String.prototype.replaceAllMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        //var matchArray = retStr.match(new RegExp(x, 'ig'));
        //for (var i = 0; i < matchArray.length; i++) {
        var prevIndex = retStr.indexOf(x); // matchkey = '*', replaceStr = '$*' While loop never ends.
        while (retStr.includes(x)) {
            retStr = retStr.replaceMatch(x, obj[x], 0);
            var replaceIndex = retStr.indexOf(x);
            if( replaceIndex <  prevIndex + (obj[x]).length) {
                break;
            } else {
                prevIndex = replaceIndex;
            }
        }
    }
    return retStr;
};
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    //var matchArray = retStr.match(new RegExp(matchkey, 'ig'));
    //for (var x = 0; x < matchArray.length; x++) {
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        }
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
        }
    }
    return retStr;
};

We can also use regular expression object for matching text with a pattern. The following are functions which will regular expression object.

You will get SyntaxError when you are using Invalid regular expression patter like '**'.

  • String.replace() function is used to replace the specified String with the given String.
  • String.match() function is to find how many time the String is repeated.
  • RegExp.prototype.test method executes a search for a match between a regular expression and a specified string. Returns true or false.
String.prototype.replaceAllRegexMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'ig'), obj[x]);
    }
    return retStr;
};

Note that regular expressions are written without quotes.


Examples to use above funtions:

var str = "yash yas $dfdas.**";
console.log('String : ', str);

// No need to escape any special Character
console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
console.log('All Matched replace : ', str.replaceAllMatches({'as' : '**', 'y':'Y', '$':'-'}));
console.log('All Matched replace : ', str.replaceAllMatches({'**' : '~~', '$':'&$&', '&':'%', '~':'>'}));

// You need to escape some special Characters
console.log('REGEX All Matched replace : ', str.replaceAllRegexMatches({'as' : '**', 'y':'Y', '\\$':'-'}));

Result:

String :  yash yas $dfdas.**
Index Matched replace :  yash yas $dfd*.**
Index Matched replace :  yash ~as $dfdas.**

All Matched replace :  Y**h Y** -dfd**.**
All Matched replace :  yash yas %$%dfdas.>>

REGEX All Matched replace :  Y**h Y** -dfd**.**

@Ashish 2019-01-29 05:05:24

Method 1

Try to implement regular expression

"Test abc test test abc test test test abc test test abc".replace(/\abc/g,' ');

Method 2

Split And join. Split with abc and join with empty space

"Test abc test test abc test test test abc test test abc".split("abc").join(" ")

@Arian saputra 2019-01-22 12:33:37

you can try like this:

example data:

var text = "heloo,hai,hei"

text = text.replace(/[,]+/g,'')

or

text.forEach(function(value){
  hasil = hasil.replace(',','')
})```

@Sandeep Gantait 2016-02-16 09:53:06

The following function works for me:

String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;

Now call the functions like this:

"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");

Simply copy and paste this code in your browser console to TEST.

@Andrés 2018-01-26 23:05:35

I just want to share my solution, based on some of the functional features of last versions of JavaScript:

   var str = "Test abc test test abc test test test abc test test abc";

   var result = str.split(' ').reduce((a, b) => {
      return b == 'abc' ? a : a + ' ' + b;   })

  console.warn(result)

@Black 2018-10-23 09:34:02

The previous answers are way too complicated. Just use the replace function like this:

str.replace(/your_regex_pattern/g, replacement_string);

Example:

var str = "Test abc test test abc test test test abc test test abc";

var res = str.replace(/[abc]+/g, "");

console.log(res);

@Ferie 2018-09-04 16:24:03

In terms of performance related to the main answers these are some online tests.

While the following are some performance tests using console.time() (they work best in your own console, the time is very short to be seen in the snippet)

console.time('split and join');
"javascript-test-find-and-replace-all".split('-').join(' ');
console.timeEnd('split and join')

console.time('regular expression');
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');
console.timeEnd('regular expression');

console.time('while');
let str1 = "javascript-test-find-and-replace-all";
while (str1.indexOf('-') !== -1) {
    str1 = str1.replace('-', ' ');
}
console.timeEnd('while');

The interesting thing to notice is that if you run them multiple time the results are always different even though the RegExp solution seems the fastest on average and the while loop solution the slowest.

@rakslice 2013-06-19 23:21:09

If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:

    function replaceMulti(haystack, needle, replacement)
    {
        return haystack.split(needle).join(replacement);
    }

    someString = 'the cat looks like a cat';
    console.log(replaceMulti(someString, 'cat', 'dog'));

@xero399 2019-08-27 07:08:45

thanks! This solution works perfectly for my problem :)

@mostafa elmadany 2017-10-07 20:56:16

If the string contain similar pattern like abccc, you can use this:

str.replace(/abc(\s|$)/g, "")

@TheAivis 2018-04-11 12:16:24

For unique replaceable values

String.prototype.replaceAll = function(search_array, replacement_array) {
  //
  var target = this;
  //
  search_array.forEach(function(substr, index) {
    if (typeof replacement_array[index] != "undefined") {
      target = target.replace(new RegExp(substr, 'g'), replacement_array[index])
    }
  });
  //
  return target;
};

//  Use:
var replacedString = "This topic commented on :year. Talking :question.".replaceAll([':year', ':question'], ['2018', 'How to replace all occurrences of a string in JavaScript']);
//
console.log(replacedString);

@rak007 2018-04-20 13:19:00

Your code doesn't work if words share the same letters. Example : var test = "Groups_4_Questions_0__Options_0_Wording".replaceAll([4, 0, 0], [100, 200, 300])

@TheAivis 2018-04-20 13:52:22

Not meant for it. Only for unique replaceable values.

@rak007 2018-04-20 13:53:03

this is useless then in most case

@csomakk 2017-12-28 12:27:42

str = str.replace(new RegExp("abc", 'g'), "");

worked better for me than the above answers. so new RegExp("abc", 'g') creates a RegExp what matches all occurence ('g' flag) of the text ("abc"). The second part is what gets replaced to, in your case empty string (""). str is the string, and we have to override it, as replace(...) just returns result, but not overrides. In some cases you might want to use that.

@yivi 2017-12-28 15:46:02

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

@csomakk 2017-12-29 17:54:34

Yeah, you're right. added. also edited it to answer the original question :)

@firstpostcommenter 2018-07-02 16:15:50

Note: g flag in regex means it is global flag which will match all occurrences

@KARTHIKEYAN.A 2017-12-28 09:44:51

In string first element search and replace

var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var i = str.replace('"[','[').replace(']"',']');
console.log(i,'//first element search and replace')

In string global search and replace

var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');
console.log(j,'//global search and replace')

@Chris Rosete 2015-06-19 21:24:21

Replacing single quotes:

function JavaScriptEncode(text){
    text = text.replace(/'/g,'&apos;')
    // More encode here if required

    return text;
}

@Stefan Đorđević 2016-12-09 22:37:51

How can i change second line to replace strings? This doesn't work: text = text.replace('hey', 'hello'); Any idea?

@Chris Rosete 2016-12-12 13:56:01

Sure Stefan, here is the code... text = text.replace(/hey/g, 'hello');

@Paulo Buchsbaum 2017-08-16 20:57:47

In my apps, I use a custom function that is the most powerful for this purpose, and even wrapping the split/join solution in the simpler case, it is a little bit faster in Chrome 60and Firefox 54 (JSBEN.CH) than other solutions. My computer runs Windows 7 64 bits.

The advantage is that this custom function can handle many substitutions at the same time using strings or characters, which can be a shortcut for some applications.

Like a split/join above solution, the solution below has no problem with escape characters, differently than regular expression approach.

  function replaceAll(s,find,repl,caseOff,byChar){
  if (arguments.length<2)  return false; 
  var destDel = ! repl;       // if destDel delete all keys from target
  var isString = !! byChar;   // if byChar, replace set of characters 
  if (typeof find !==typeof repl && ! destDel)  return false; 
  if (isString  &&  (typeof find!=="string"))   return false; 

  if (! isString &&  (typeof find==="string"))  {
    return s.split(find).join(destDel?"":repl);
  }

  if ((! isString)  &&  ( ! Array.isArray(find) ||
          ( ! Array.isArray(repl) && ! destDel)   ))  return false;

     // if destOne replace all strings/characters by just one element
  var destOne = destDel ? false : (repl.length===1);   

     // Generally source and destination should have the same size
  if (! destOne && ! destDel && find.length!==repl.length)  return false    

  var prox,sUp,findUp,i,done;   
  if (caseOff)  {    // case insensitive    
       // Working with uppercase keys and target 
    sUp = s.toUpperCase();   
    if (isString)
       findUp = find.toUpperCase()   
    else
       findUp = find.map(function(el){  return el.toUpperCase();});    

  } else  {         // case sensitive
     sUp = s;
     findUp =find.slice();  // clone array/string
  }  

  done = new Array(find.length);  // size: number of keys
  done.fill(null);              

  var pos = 0;       // initial position in target s
  var r = "";   // initial result
  var aux, winner;
  while (pos < s.length)  {       // Scanning the target
     prox  = Number.MAX_SAFE_INTEGER;
     winner = -1;  // no winner at start
     for (i=0;i<findUp.length;i++)   // find next occurence for each string
       if (done[i]!==-1) {    // key still alive
             // Never search for the word/char or is over?
         if (done[i]===null || done[i]<pos)  { 
           aux = sUp.indexOf(findUp[i],pos);
           done[i]=aux;  // Save the next occurrence
         } else
           aux = done[i]   // restore the position of last search
         if (aux<prox && aux!==-1) {   // if next occurrence is minimum
           winner = i;     // save it  
           prox = aux;
         }  
       }  // not done

      if (winner===-1) {   // No matches forward
         r += s.slice(pos);   
         break;
      } // no winner

      // found the character or string key in the target

      i = winner;  // restore the winner
      r += s.slice(pos,prox);   // update piece before the match

            // Append the replacement in target 
      if (! destDel) r += repl[ destOne?0:i ];  
      pos = prox + ( isString?1:findUp[i].length );       // go after match

  }  // loop
  return r;  // return the resulting string
}

The documentation is below

           replaceAll    
 Syntax    
 ======     
      replaceAll(s,find,[ repl ,caseOff, byChar)     

 Parameters    
 ==========    

   "s" is a string target of replacement.    
   "find" can be a string or array of strings.     
   "repl" should be the same type than "find" or empty     

  if "find" is a string, it is a simple replacement for      
    all "find" occurrences in "s" by string "repl"    

  if "find" is an array, it will replaced each string in "find"    
    that occurs in "s" for corresponding string in "repl" array.
  The replace specs are independent: A replacement part cannot    
    be replaced again. 


  if "repl" is empty all "find" occurrences in "s" will be deleted.   
  if "repl" has only one character or element,    
      all occurrences in "s" will be replaced for that one.   

  "caseOff" is true if replacement is case insensitive     
       (default is FALSE)

  "byChar" is true when replacement is based on set of characters.    
  Default is false   

  if "byChar", it will be replaced in "s" all characters in "find"   
  set of characters for corresponding character in  "repl"
  set of characters   

 Return   
 ======   
  the function returns the new string after the replacement.  

To be fair, I ran the benchmark with no parameter test.

Here is my test set, using Node.js

function l() { return console.log.apply(null, arguments); }

var k=0;
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"],["do","fa"]));  //1
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"],["do"]));  //2
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"]));  //3
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
     "aeiou","","",true));  //4
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou","a","",true));  //5
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou","uoiea","",true));  //6
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou","uoi","",true));  //7
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"],["do","fa","leg"]));  //8
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
      ["ri","nea"],["do","fa"]));  //9
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
      ["ri","nea"],["do","fa"],true)); //10
return;

And the results:

1 'banana is a dope fruit harvested far the dover'
2 'banana is a dope fruit harvested dor the dover'
3 'banana is a pe fruit harvested r the ver'
4 'bnn s rp frt hrvstd nr th rvr'
5 'banana as a rapa fraat harvastad naar tha ravar'
6 'bununu is u ripo frait hurvostod nour tho rivor'
7 false
8 false
9 'BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER'
10 'BANANA IS A doPE FRUIT HARVESTED faR THE doVER'

@Bart Read 2017-09-04 06:53:24

Downvoted because using this much code to achieve something so basic feels overkill to me.

@Paulo Buchsbaum 2017-09-05 18:34:34

It's matter of opinion. For me It's a powerhouse and fast function. I've used for years. One cannot do it on fewer lines. For those who just want to replace chars and pieces in strings without worrying about escape characters from regular expressions, it might be a good choice. The number of lines does not matter much, since it works is a tested black box

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] How to check if a string contains a substring in Bash

  • 2008-10-23 12:37:31
  • davidsheldon
  • 1897909 View
  • 2341 Score
  • 23 Answer
  • Tags:   string bash substring

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

43 Answered Questions

[SOLVED] Sort array of objects by string property value

42 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

85 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

65 Answered Questions

[SOLVED] What is the difference between String and string in C#?

3 Answered Questions

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

6 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

34 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3737045 View
  • 1564 Score
  • 34 Answer
  • Tags:   java string

Sponsored Content