gpt4 book ai didi

Javascript 在字符串中查找单词的索引(不是单词的一部分)

转载 作者:可可西里 更新时间:2023-11-01 02:31:56 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

> '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

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

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

关于Javascript 在字符串中查找单词的索引(不是单词的一部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com