2

I want to replace all + symbols in a JavaScript String with a space. Based on this thread Fastest method to replace all instances of a character in a string and this thread How to replace all dots in a string using JavaScript I do:

soql = soql.replace(/+/g, " ");

But that gives:

SyntaxError: invalid quantifier

Any ideas how I do it?

Community
  • 1
  • 1
More Than Five
  • 9,959
  • 21
  • 77
  • 127
  • Mostly likely you are trying to parse some search parameters that came from the URL?? in that case the correct answer is https://stackoverflow.com/a/57018898/1812732 – John Henckel Aug 19 '20 at 18:55

2 Answers2

12

You need to escape the + since it is a special character in regex meaning "one or more of the previous character." There is no previous character in /+/, so the regex does not compile.

soql = soql.replace(/\+/g, " ");
//or
soql = soql.replace(/[+]/g, " ");
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
5

Try escaping the +:

soql = soql.replace(/\+/g, " ");

The + in a regular expression actually means "one or more of the previous expression (or group)". Escaping it tells that you want a literal plus sign ("+").

More information on quantifiers is available if you google it. You might also want to look into the Mastering Regular Expressions book.

gpojd
  • 22,558
  • 8
  • 42
  • 71