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

0

2 Answers 2

3

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)
)

Sign up to request clarification or add additional context in comments.

2 Comments

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?
RegEx takes flags as the second parameter, new RegExp('\\b' + this.input, 'i'); will give you a case-insensitive regex
1

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-

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.