26

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.

1
  • 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); } Commented Aug 25, 2020 at 5:51

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

4

You need to use regexp here. Please try following

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

g means replace it globally.

Comments

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");

2 Comments

Thank you sir, have you compared the performance difference to Regex? I could not get Regex global replace working...
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.