3
<body class="reviews"></body>

var body = document.body;
var target = 'reviews';

if (body.className.match('/\b' + target + '\b/'))
    console.log(true);
else
    console.log(false);

This code returns false. But if I use body.className.match(/\breviews\b/) it returns true.

What's wrong with it?

I tried to escape a variable in a regex, no luck.

1

1 Answer 1

3

You are searching for the literal string '/\breviews\b/', it's not being read as a RegEx.

You need to use the new RegExp method.

body.className.match(new RegExp('\\b' + target + '\\b'))

Note: Don't use delimiters with new RegExp. Also, note that \\b has 2 \.

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

2 Comments

Double-escape the \\b inside the quoted string?
@MichaelBerkowski: Thanks, forgot about that :-)

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.