1

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

3 Answers 3

5

| is a special character in regex. You need to escape it with a backslash.

string1.replace(/\|/g,",");

Live example

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

Comments

5

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

Comments

3

You didn't escape the pipe character in the regular expression:

var string1 = "one|two|three|four";
string1.replace(/\|/g,",")

6 Comments

I look late to the party now... dang researching.
You need to know this stuff my heart or you'll never be competitive on SO, haha
I always think I know, but I still have to check to make sure. Probably why I'm still under 1K. Oh well! :)
Strange though that my answer was just as helpful as the others (if a minute or two behind), but no upvotes at all.
it's a harsh world haha. But you're well on your way. Here, have an upvote, and good luck for the rest!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.