Javascript在字符串中找到单词的索引(不是单词的一部分) [英] Javascript find index of word in string (not part of word)

查看:119
本文介绍了Javascript在字符串中找到单词的索引(不是单词的一部分)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 str.indexOf(word)来查找字符串中的单词。
但问题在于它还会返回其他单词的部分内容。

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.

示例:我去了foobar并订购了foo。
我想要单词foo的第一个索引,而不是foobar中的foo。

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.

我无法搜索foo因为有时它可能后跟一个句号或逗号(任何非字母数字字符)。

I can not search for "foo " because sometimes it might be followed by a full-stop or comma (any non-alphanumeric character).

推荐答案

你必须使用正则表达式为此:

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 / 匹配由字边界包围的 foo

/\bfoo\b/ matches foo that is surrounded by word boundaries.

要匹配任意单词,请构建一个 RegExp 对象:

To match an arbitrary word, construct a RegExp object:

> var word = 'foo';
> var regex = new RegExp('\\b' + word + '\\b');
> 'I went to the foobar and ordered foo.'.search(regex);
33

这篇关于Javascript在字符串中找到单词的索引(不是单词的一部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆