1
"-x-x+x".replace('-', '+')

equals

"+x-x+x"

why isn't the second - replaced?

3
  • 1
    .replace only replace the first instance(character). to replace all instances you have to use regex.. console.log('-x-x+x'.replace(/-/g, '+')); Commented Jan 22, 2020 at 22:01
  • Searching StackOverflow for "[javascript] replace all instances" pulls up many duplicate posts asking essentially the same question. Commented Jan 22, 2020 at 22:08
  • @Taplar It doesn't answer why Commented Jan 22, 2020 at 22:10

3 Answers 3

2

.replace only replaces the first instance it finds. To replace all of them, use a regex:

"-x-x+x".replace(/-/g, '+')

Note the /g at the end of the regex: it indicates "global" mode. Without it you'll still only replace the first instance.

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

1 Comment

Thanks for this, I was trying to find what the /g meant.
1

Convert it to regex to replace all.

console.log("-x-x+x".replace(/-/g, '+'))

Comments

1

This is explained in the documentation for String#replace:

enter image description here

Use a regular expression:

'-x-x+x'.replace(/-/g, '+')
//=> "+x+x+x"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.