Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 863
Omar Tariq Avatar asked Apr 02 '14 20:04

Omar Tariq


People also ask

How do you replace a string with spaces?

replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace all characters in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do you replace all values in a string?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

How do you replace a character in a string with spaces in Java?

In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.


1 Answers

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,' ')... 
like image 114
p.s.w.g Avatar answered Sep 21 '22 13:09

p.s.w.g