0
var string = "This is a string";
var key = "Th"; 
var patt = new RegExp(/\b key /, "i");

if(patt.test(string)){
    alert("true");
}

How can I escape \b so I can use the key variable?

Thanks in advance!

2

1 Answer 1

2

Don't use a regular expression literal when using the RegExp constructor.

When you want a \ in a string literal, you have to escape it as \\.

Here's the code :

var patt = new RegExp("\\b " + key + " ", "i");
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not positive, but don't you still need the delimiters?
If you mean the /, they're what defines a regular expression literal. So no, you can't use them when you want to use a variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.