30

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

4
  • 6
    i.split('+').join(' ') comes to mind, if you'd like to avoid regex. Commented Apr 2, 2014 at 20:42
  • @adeneo nice. more generalized replace all, would work on any substring in a string. should I be worried with the cost of splitting and joining? Commented Apr 2, 2014 at 20:44
  • I wouldn't think efficiency is an issue -> jsperf.com/split-vs-regexppp Commented Apr 2, 2014 at 20:57
  • Looks like you want to parse a URL. Then just use the URL API. Commented Aug 3, 2021 at 15:40

1 Answer 1

90

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,' ')...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.