Reputation: 323
I have a problem with the replace method of javascript. I have a string that is:
string1 = one|two|three|four;
I wanted to replace("|" with ",");
I tried:
string1.replace("|", ",");
but is replacing only the first occurence. I also tried:
string1.replace(/|/g,",");
and result was:
string1 = "o,n,e,|,t,w,o,|,t,h,r,e,e,";
how can i make it the one below?
string1 = "one,two,three";
Thanks a lot, tinks
Upvotes: 1
Views: 111
Reputation: 14987
You didn't escape the pipe character in the regular expression:
var string1 = "one|two|three|four";
string1.replace(/\|/g,",")
Upvotes: 3
Reputation: 47776
|
is a special character in regex. You need to escape it with a backslash.
string1.replace(/\|/g,",");
Upvotes: 5
Reputation: 270617
|
is a special character in regular expressions which makes an or selection between the left and right operands, and you must escape it with a backslash to use it as a literal character.
string1.replace(/\|/g,",");
string1 = "one|two|three|four";
"one|two|three|four"
string1.replace(/\|/g, ",");
"one,two,three,four"
Upvotes: 5