0

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: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    //val.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

    //from: https://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

Community
  • 1
  • 1
Emil Devantie Brockdorff
  • 4,724
  • 12
  • 59
  • 76

2 Answers2

1

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

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

Working fiddle

Amit
  • 45,440
  • 9
  • 78
  • 110