1

I trying to get user input match it against a string variable, when I passed a literal string to new RegExp(/\bjavascript/), it works, but I tried new RegExp('\b' + this.input) or new RegExp('/\b' + this.input + '/'); it fails.

Here is the code

 var lang = 'javascript'
 let patern =  new RegExp('/\b' + this.input + '/');
 console.log(patern.test('lang'));

where 'input' is declare within my class

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
yaxx
  • 529
  • 1
  • 6
  • 22

2 Answers2

2

Remove the slash from the beginning and end and escape backslashes:

this.input = "St";

let pattern =  new RegExp('\\b' + this.input, 'i');

console.log(
  "Stack Overflow".match(pattern)
)
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • Thanks Luca that works but i tried adjust it to be case insensitive like: let pattern = new RegExp('\\b' + this.input + '\\i'); but fail again any reason why? – yaxx Sep 15 '18 at 14:23
  • RegEx takes flags as the second parameter, `new RegExp('\\b' + this.input, 'i');` will give you a case-insensitive regex – Luca Kiebel Sep 15 '18 at 14:25
0

When input comes from a user, it's a good idea to escape the string using the following:

RegExp.escape = function (s)
{
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

You call it like this:

 let patern =  new RegExp('\\b' + RegExp.escape(this.input));

That way it Works even when the input has special characters in it, like '\' or parenthesis-

Poul Bak
  • 10,450
  • 5
  • 32
  • 57