6

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?

1
  • new RegExp('AB|AG|AS|Ltd|KB|University', 'g') or /AB|AG|AS|Ltd|KB|University/g but not a combination of the two :) Commented Jun 11, 2014 at 7:06

1 Answer 1

21

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');
Sign up to request clarification or add additional context in comments.

6 Comments

could I somehow insert a string between / myVarHere / g ?
Awesome! Accepting asap :)
@dystroy Would the accepted words not need to be surrounded by word boundaries, \b otherwise you could get matches when the accepted words appear within other words. See here: regex101.com/r/zS8dT9
|

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.