Alosyius
Alosyius

Reputation: 9121

JavaScript check if string contains any of the words from regex

I'm trying to check if a string contains any of these words:

AB|AG|AS|Ltd|KB|University

My current code:

var acceptedwords = '/AB|AG|AS|Ltd|KB|University/g'
var str = 'Hello AB';

var matchAccepted = str.match(acceptedwords);
console.log(matchAccepted);

if (matchAccepted !== null) { // Contains the accepted word
    console.log("Contains accepted word: " + str);          

} else {
    console.log("Does not contain accepted word: " + str);

}

But for some strange reason this does not match.

Any ideas what I'm doing wrong?

Upvotes: 6

Views: 17735

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382150

That's not the right way to define a literal regular expression in Javascript.

Change

var acceptedwords = '/AB|AG|AS|Ltd|KB|University/g'

to

var acceptedwords = /AB|AG|AS|Ltd|KB|University/;

You might notice I removed the g flag : it's useless as you only want to know if there's one match, you don't want to get them all. You don't even have to use match here, you could use test :

var str = 'Hello AB';
if (/AB|AG|AS|Ltd|KB|University/.test(str)) { // Contains the accepted word
    console.log("Contains accepted word: " + str);          
} else {
    console.log("Does not contain accepted word: " + str);
}

If you want to build a regex with strings, assuming none of them contains any special character, you could do

var words = ['AB','AG', ...
var regex = new RegExp(words.join('|'));

If your names may contain special characters, you'll have to use a function to escape them.

If you want your words to not be parts of other words (meaning you don't want to match "ABC") then you should check for words boundaries :

regex = new RegExp(words.map(function(w){ return '\\b'+w+'\\b' }).join('|'),'g');

Upvotes: 21

Related Questions