Omar Tariq
Omar Tariq

Reputation: 7724

Replace all plus signs (+) with space in a string

I'm not sure how to escape '+' in regex. Plus can come multiple times in i so we need to replace all + in the string. Here's what I have:

i.replace(new RegExp("+","g"),' ').replace(new RegExp("selectbasic=","g"),'').split('&');

But this gives me this error:

Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat

Upvotes: 30

Views: 49973

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

The + character has special significance in regular expressions. It's a quantifier meaning one or more of the previous character, character class, or group.

You need to escape the +, like this:

i.replace(new RegExp("\\+","g"),' ')...

Or more simply, by using a precompiled expression:

i.replace(/\+/g,' ')...

Upvotes: 90

Related Questions