Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I'm working on some regex for a input text field and have had some trouble escaping special characters such as "+" or "?".

I've used these two questions for doing so and they work for a string such as c+ but if I enter c++ I get following error in the console Invalid regular expression: /c++/: Nothing to repeat

Here's the code:

$('input').keyup(function(){
   var val = $(this).val().trim().toLowerCase();
    // from: http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    //val.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

    //from: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
    val = val.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");

    var re = new RegExp(val, 'ig');
    console.log(re);
});

Here is a jsFiddle example of the issue

Thanks

share|improve this question

2 Answers 2

up vote 1 down vote accepted

There's a bug in your code. As a string is immutable in JavaScript, replace doesn't change it but returns a new one. You do the replacement but you doesn't take the returned value

Change

val.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");

to

val = val.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");

Demonstration

share|improve this answer
    
Oh yes of cause, I feel so silly. Thank you so much :-) – Mestika Jun 23 at 11:12

Your regex was fine, you just threw away the result of the replace call. Replace with val = val.replace(...);

Working fiddle

share|improve this answer
    
Thank you so much - it was so easy :-) – Mestika Jun 23 at 11:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.