Tyler
Tyler

Reputation: 874

If $(element).text() Is In String

What I'm doing...

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.

Question

Why doesn't my match() work and what is my best way to resolve?

Upvotes: 0

Views: 110

Answers (3)

poushy
poushy

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

baao
baao

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

Anthony C
Anthony C

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

Related Questions