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

equals

"+x-x+x"

why isn't the second - replaced?

abdhalees
  • 79
  • 6

3 Answers3

1

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

Alastair
  • 5,655
  • 7
  • 32
  • 58
1

Convert it to regex to replace all.

console.log("-x-x+x".replace(/-/g, '+'))
Addis
  • 2,420
  • 2
  • 11
  • 20
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"
customcommander
  • 14,568
  • 4
  • 48
  • 68