且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript/jQuery-如何检查字符串是否包含特定单词

更新时间:2023-11-25 23:53:52

如果您要查找确切的单词,并且不希望它与梦m"之类的东西相匹配(这可能就是您所需要的)需要),则可以使用正则表达式:

If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)

如果只想查找字符"are",请使用indexOf.

If you just want to find the characters "are", then use indexOf.

如果要匹配任意单词,则必须基于单词字符串以编程方式构造RegExp(正则表达式)对象本身,并使用test.

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.