开发者

Find "word" index in paragraph with jQuery (Javascript)

开发者 https://www.devze.com 2023-01-20 16:36 出处:网络
I have a string that represents a paragraph of text. var paragraph = \"It is important that开发者_StackOverflow中文版 the word cold is not partially selected where we search for the word old\";

I have a string that represents a paragraph of text.

var paragraph = "It is important that开发者_StackOverflow中文版 the word cold is not partially selected where we search for the word old";

I want to be able to search this paragraph for the index of a "word" and have it do an exact match on a "word". For example, when searching for "old". I should only get 1 result, not 2 since matching the "old" in "cold" is invalid.


You need to use the word-boundary search \b:

var idx = paragraph.search(/\bold\b/i);

This matches things like white space, dashes etc. that separate words.

0

精彩评论

暂无评论...
验证码 换一张
取 消