<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.
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 \.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With