admin管理员组

文章数量:1425666

I have input box on my page which contains strings separated by + such as:

this+is+my+string

On page load i want to replace all + with a blank. I have tried:

var str = $('#MyText1');

str = str.replace(/+/gi, ' ');

However i am getting the following error:

SyntaxError: invalid quantifier

Please note my application is using Angular v.1.2.8

I have input box on my page which contains strings separated by + such as:

this+is+my+string

On page load i want to replace all + with a blank. I have tried:

var str = $('#MyText1');

str = str.replace(/+/gi, ' ');

However i am getting the following error:

SyntaxError: invalid quantifier

Please note my application is using Angular v.1.2.8

Share Improve this question asked Jul 17, 2014 at 11:44 Oam PsyOam Psy 8,66335 gold badges97 silver badges167 bronze badges 3
  • 1 "escape" the plus sign -> str = str.replace(/\+/gi, ' '); then it works. – davidkonrad Commented Jul 17, 2014 at 11:46
  • @davidkonrad - With the above, i am seeing error: Error: str.replace is not a function Is this because i am using Angular? – Oam Psy Commented Jul 17, 2014 at 11:52
  • have posted an answer, you also forget to extract the value from the input, you just reference the input box itself, and that has no .replace() method. – davidkonrad Commented Jul 17, 2014 at 12:00
Add a ment  | 

3 Answers 3

Reset to default 5

+ is indeed a quantifier in regular expressions (meaning "1 or more").

You're close with your syntax -- try

str = str.replace(/\+/g, ' ');

You forget to extract the content of the input box :

var str = $('#MyText1').val();
                        ^^^^^

now the escape will work :

str = str.replace(/\+/gi, ' ');

see demo -> http://jsfiddle/8TKWZ/

You are replacing using a regular expression. In a regular expression, '+' has special meaning. However, you don't want that special meaning, you want the literal character. As such, you must escape the '+'

str = str.replace(/\+/gi, ' ');

本文标签: jqueryJavascripthow to replace allin a string with a blank spaceStack Overflow