Rohit Rohit - 5 months ago 14
Javascript Question

Why replace() is not working for '$' symbol?

I want to replace all the '$' in a string, I am using simple

replace()
function. It is working for other substring but not for '$' symbol. Any reason why?



var mystring = "this,is,a,test"
console.log(mystring.replace(/,/g , ":"));

var mystring2 = "this$is$a$test"
console.log(mystring2.replace(/$/g , ":"));




Answer

$ has special meaning in a regular expression, it matches the end of the string. You need to escape it to use it literally.

var mystring = "this,is,a,test"
console.log(mystring.replace(/,/g , ":"));

var mystring2 = "this$is$a$test"
console.log(mystring2.replace(/\$/g , ":"));

You should read an regular expression tutorial, like the one at regular-expressions.info