javascript Javascript在字符串中查找单词的索引(不是单词的一部分)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12773913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript find index of word in string (not part of word)
提问by Blender
I am currently using str.indexOf("word")
to find a word in a string.
But the problem is that it is also returning parts of other words.
我目前正在使用str.indexOf("word")
在字符串中查找单词。但问题是它也返回了其他词的部分内容。
Example: "I went to the foobar and ordered foo." I want the first index of the single word "foo", not not the foo within foobar.
示例:“我去了 foobar 并订购了 foo。” 我想要单个单词“foo”的第一个索引,而不是 foobar 中的 foo。
I can not search for "foo " because sometimes it might be followed by a full-stop or comma (any non-alphanumeric character).
我无法搜索“foo”,因为有时它后面可能跟有句号或逗号(任何非字母数字字符)。
回答by Blender
You'll have to use regex for this:
您必须为此使用正则表达式:
> 'I went to the foobar and ordered foo.'.indexOf('foo')
14
> 'I went to the foobar and ordered foo.'.search(/\bfoo\b/)
33
/\bfoo\b/
matches foo
that is surrounded by word boundaries.
/\bfoo\b/
foo
被单词边界包围的匹配项。
To match an arbitrary word, construct a RegExp
object:
要匹配任意单词,请构造一个RegExp
对象:
> var word = 'foo';
> var regex = new RegExp('\b' + word + '\b');
> 'I went to the foobar and ordered foo.'.search(regex);
33
回答by RobG
For a general case, use the RegExp constrcutor to create the regular expression bounded by word boundaries:
对于一般情况,使用 RegExp 构造器创建以字边界为界的正则表达式:
function matchWord(s, word) {
var re = new RegExp( '\b' + word + '\b');
return s.match(re);
}
Note that hyphens are considered word boundaries, so sun-dried is two words.
请注意,连字符被视为单词边界,因此晒干是两个单词。
回答by P.O.W.
I have tried both with ".search" and ".match", as suggested in the previous answers, but only this solution worked for me.
正如前面的答案中所建议的那样,我已经尝试过“.search”和“.match”,但只有这个解决方案对我有用。
var str = 'Lorem Ipsum Docet';
var kw = 'IPSUM';
var res = new RegExp('\b('+kw+')\b','i').test(str);
console.log(res); // true (...or false)
With the 'i' for case insensitive search.
使用“i”进行不区分大小写的搜索。