25

I am using below code to replace , with \n\t

ss.replace(',','\n\t')

and i want to replace all the coma in string with \n so add this ss.replaceAll(',','\n\t') it din't work..........!

any idea how to get over........?

thank you.

Warrior
  • 3,184
  • 12
  • 44
  • 53
  • One way can be you can extend String class in your app `String.prototype.replaceAll = function(fromReplace, toReplace){ return this.replace(new RegExp(fromReplace, 'ig'), toReplace); }` – Mohit Yadav Aug 25 '20 at 05:51

3 Answers3

31

You need to do a global replace. Unfortunately, you can't do this cross-browser with a string argument: you need a regex instead:

ss.replace(/,/g, '\n\t');

The g modifer makes the search global.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
4

You need to use regexp here. Please try following

ss.replace(/,/g,”\n\t”)

g means replace it globally.

Eldar Djafarov
  • 23,327
  • 2
  • 33
  • 27
2

Here's another implementation of replaceAll.

String.prototype.replaceAll = function (stringToFind, stringToReplace) {
    if (stringToFind === stringToReplace) return this;
    var temp = this;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
};

Then you can use it like:

var myText = "My Name is George";                                            
var newText = myText.replaceAll("George", "Michael");
woof
  • 83
  • 2
  • 8
scripto
  • 2,297
  • 1
  • 14
  • 13
  • Thank you sir, have you compared the performance difference to Regex? I could not get Regex global replace working... – RBILLC May 15 '20 at 20:21
  • This will go into an infinite loop if the stringToFind includes part of the stringToReplace. Consider keeping a record of the current index (starting at -1) and have the while loop check if the next index is greater than the current index. – Adam Jan 10 '22 at 09:27