By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,883 Members | 2,037 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,883 IT Pros & Developers. It's quick & easy.

How to modify a RegEx to accept a + sign

Claus Mygind
100+
P: 571
The function below takes a string and highlights the text within the string that matches the search criteria. It works fine unless the user includes the + sign. Then this line
var re = new RegExp('(' + searchStr + ')', 'gi');
generates a "SyntaxError: invalid quantifier"

So obviously the + has to be escaped \+. Can that be added to the RegEx expression or does that have to be tested and inserted first?



Expand|Select|Wrap|Line Numbers
  1. function HighlightSearchValue(oObj, searchStr, addLineBreak)
  2. {
  3.     /*
  4.     -------------------------------------------
  5.     this function higlights the section of text
  6.     which the user entered as a search criteria
  7.     -------------------------------------------
  8.     */
  9.  
  10.     var re  = new RegExp('(' + searchStr + ')', 'gi');
  11.  
  12.     var ret = oObj.split(re);
  13.  
  14.     for (var i = 0, l = ret.length; i < l; i++) {
  15.         if (re.test(ret[i])) {
  16.             ret[i] = ret[i].replace(re, '<span style="color:red;">' + ret[i] + '</span>');
  17.         }
  18.     }
  19.     var result = ret.join('')+(( addLineBreak) ? '<br/>':'');
  20.  
  21.     return result;
  22.  
  23. }
  24.  
Jun 10 '13 #1

✓ answered by Dormilich

Can that be added to the RegEx expression or does that have to be tested and inserted first?
if RegExp could mask their special characters, what would there be left from the RegExp?

So I guess you need to do it beforehand. splitting and re-joining the string seems like an easy way for it.
Expand|Select|Wrap|Line Numbers
  1. function escape_plus(str)
  2. {
  3.     return str.split('+').join('\\+');
  4. }

Share this Question
Share on Google+
1 Reply


Dormilich
Expert Mod 5K+
P: 8,639
Can that be added to the RegEx expression or does that have to be tested and inserted first?
if RegExp could mask their special characters, what would there be left from the RegExp?

So I guess you need to do it beforehand. splitting and re-joining the string seems like an easy way for it.
Expand|Select|Wrap|Line Numbers
  1. function escape_plus(str)
  2. {
  3.     return str.split('+').join('\\+');
  4. }
Jun 10 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.