Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable in match (javascript)

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

like image 524
Mark Avatar asked Feb 03 '26 22:02

Mark


1 Answers

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 \.

like image 182
Rocket Hazmat Avatar answered Feb 06 '26 10:02

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!