1

This is possibly a duplicate but I just cant figure out what is wrong with this regular expression.

<p id="demo">Result comes here:</p>
<button onclick="myFunction()">Check</button>

<script>
function myFunction()
{
    var str = "The best things in life are free";
    var sTerm="things";
    var regXSearch= "/\\b"+sTerm+"/gi";
    var regX = new RegExp(regXSearch);
    //var regX= new RegExp(/\bthings/gi);
    var result = regX.test(str);

    document.getElementById("demo").innerHTML=result;
}
</script>

For some reason this returns false. If I check the value of the regXSearch variable it will be exacly the same as what is in the regX RegExp that is commented out. And that is in fact returning true.

1 Answer 1

2

You're combining the two different regex syntaxes. Try this:

var regXSearch= "\\b"+sTerm;
var regX = new RegExp(regXSearch, "gi");

You can use regex literals such as

/\bthings/gi

or you can use the RegExp constructor function like this:

new RegExp("\\bthings", "gi")

Although I can see no good reason to do so, you could also even do

new RegExp(/\bthings/gi)

But yours is an illegal mix of these:

new RegExp("/\\bthings/gi");  // DON'T DO THIS!  :-)
Sign up to request clarification or add additional context in comments.

1 Comment

how do I then use variable as the hambugger here: > db.restaurants.find( { cuisine: /Hamburgers/ } ).count()

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.