Search code examples
javascriptjquerywords

Looking for multiple words js Jquery


I'm trying to write a simple if statement that looks to see if a word matches some other words. I can get this to work when I use just one word but not with multiple words like below. When I use if (||). I would like to use "contains" but can't see how to use this with a var

Also: ("Woven || Main") is a var so I need this part to stay together.

var option="Woven || Main";

This does not work:

var titleIs = "Knit";

if (titleIs.match("Woven || Main")) {

    alert("Main")

}

This works:

var titleIs = "Knit";

if (titleIs.match("Woven")) {

    alert("Main")

}

Solution

  • var words = ['Woven', 'Main'];
    var regex = new RegExp('^(' + words.join('|') + ')$');
    
    if (regex.test(titleIs)) {...}