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

equals

"+x-x+x"

why isn't the second - replaced?

abdhalees
  • 79
  • 1
  • 7

3 Answers3

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.

Alastair
  • 5,894
  • 7
  • 34
  • 61
1

Convert it to regex to replace all.

console.log("-x-x+x".replace(/-/g, '+'))
Addis
  • 2,480
  • 2
  • 13
  • 21
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
  • 17,580
  • 5
  • 58
  • 84