Reputation: 874
I would like to have a string as such:
var match = "abcd|efhi|jklm|nopq|rstu|vwxyz";
And then check whether $(element).text()
is one of the match.split("|")
or simply within match
.
I thought I'd be able to do if($('element').text().toLowerCase().match(/^(match)$/)) {
however this wouldn't work.
Why doesn't my match()
work and what is my best way to resolve?
Upvotes: 0
Views: 110
Reputation: 1134
To match a variable string, you can create a Regexp object:
var match = "^(abcd|efhi|jklm|nopq|rstu|vwxyz)$";
var reg = new RegExp(match, 'g');
if($('element').text().toLowerCase().match(reg)) {}
To make it case insensitive:
var match = "^(abcd|efhi|jklm|nopq|rstu|vwxyz)$";
var reg = new RegExp(match, 'ig');
if($('element').text().match(reg)){}
Upvotes: 0
Reputation: 73241
Your best way to resolve is to assign a regex to match
var match = /^(abcd|efhi|jklm|nopq|rstu|vwxyz)$/i;
Note that I added i
for case insensitivity, so you can get rid of toLowerCase()
if($('element').text().match(match)) {
//...
}
Upvotes: 3
Reputation: 2157
My approach without using RegEx
var match = "abcd|efhi|jklm|nopq|rstu|vwxyz".split('|');
if (match.indexOf($('element').text().toLowerCase()) !== -1) {
// match found
}
Upvotes: 2