最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript check if string contains any of the words from regex - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Jun 11, 2014 at 7:05 Denys Séguret 382k90 gold badges810 silver badges775 bronze badges asked Jun 11, 2014 at 7:03 AlosyiusAlosyius 9,11126 gold badges78 silver badges121 bronze badges 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 :) – Ja͢ck Commented Jun 11, 2014 at 7:06
Add a comment  | 

1 Answer 1

Reset to default 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');
发布评论

评论列表(0)

  1. 暂无评论