The third parameter of String.prototype.replace()
function was never defined as a standard, so most browsers simply do not implement it.
g
(global) flag.var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr ); // "this-is-a-test"
_x000D_
It is important to note, that regular expressions use special characters that need to be escaped. As an 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).
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr ); // "this-is-a-test"
_x000D_
If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp
object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \
when included in a string) will be necessary.
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr ); // "this-is-a-test"
_x000D_