431

I have a string with multiple commas, and the string replace method will only change the first one:

var mystring = "this,is,a,test"
mystring.replace(",","newchar", -1)

Result: "thisnewcharis,a,test"

The documentation indicates that the default replaces all, and that "-1" also indicates to replace all, but it is unsuccessful. Any thoughts?

1

3 Answers 3

904

The third parameter of the String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it. It was eventually removed and replaced with String.prototype.replaceAll() (see below).


Modern solution (2022)

Use String.prototype.replaceAll(). It is now supported in all browsers and NodeJS.

var myStr = "this,is,a,test";
var newStr = myStr.replaceAll(",", "-");

console.log( newStr );  // "this-is-a-test"


The old way is to use a regular expression with g (global) flag

var myStr = "this,is,a,test";
var newStr = myStr.replace(/,/g, "-");

console.log( newStr );  // "this-is-a-test"

Have issues with regular expressions?

It is important to note, that regular expressions use special characters that need to be escaped. For example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

If you need to pass a variable as a replacement string, instead of using regex literal you may create a RegExp object and pass a string as its first argument. The usual escape rules (preceding special characters with \ when included in a string) will be necessary.

function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

var myStr = "this.is.a.test";
var reStr = escapeRegex(".");
var newStr = myStr.replace(new RegExp(reStr, "g"), "-");

console.log( newStr );  // "this-is-a-test"

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

9 Comments

Excellent answer. /g makes global search of comma and replacing it in entire string.It works this way, Am I correct??
Can you please describe in details regarding /"Seprator"/g
@MSTdev This is a typical regular expression with g flag (a.k.a. "global search"). The algorithm is simple: regular expression finds ALL matches (here commas) in the given string. More information about regular expressions in JavaScript you can find in MDN.
Not working in TypeScript.
@chows2603 use /\\/g and it will work.
|
185

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

6 Comments

This works w/o Regex, globaly, with variables and special characters (ex: '['+variable+']'). Genius.
it's a good answer, I tested the replace function with dots '.' but it doesn't work as expected, but you answer made it good
@SrednyMCasanova that is because in regex, the period is a special character, and you should escape it with \. Example: var mystring = "this.,.is.,.a.,.test"; mystring.replace(/\./g , "|"); See MDN RegExp - Special characters meaning in regular expressions
is it slower/faster than regex with /g?
@CSchwarz - I was about to make the edit for you but then remembered that many JS semicolons are optional including these. Many developers very adamantly insist on including them anyway. While I have no qualms about editing answers if I'm 100% sure (exception: took me 2 days to muster courage to edit one of Atwood's answers, lol), but in this case I'll leave it as-is. You'll be able to edit at 2000 rep. 😉
|
52
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

3 Comments

not working for var mystring = "this,is.a.test" mystring.replace(/./g, ">"); It replace the whole string
@DineshJain In regex dot (.) has a special meaning, it means every char, and like all other special chars, needs to be escaped with ` if you want to use their value "literally". if you want to replace only dots you need to use \.`.
I added the String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; solves my problem @gdoron Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.