最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript How to check if a word exists in a string - Stack Overflow

programmeradmin2浏览0评论

I want to check whether a word exists in a string. I tried to use search() function, but it also counts the words containing the searched word. For example, let my string be

var str = "This is a pencil.";

When I search for "is"

str.search("is");

gives 2 while I want to get 1 which should be only "is", not "This". How can I achieve this?

Thanks in advance...

I want to check whether a word exists in a string. I tried to use search() function, but it also counts the words containing the searched word. For example, let my string be

var str = "This is a pencil.";

When I search for "is"

str.search("is");

gives 2 while I want to get 1 which should be only "is", not "This". How can I achieve this?

Thanks in advance...

Share Improve this question asked May 16, 2017 at 19:38 Enes AltuncuEnes Altuncu 4392 gold badges7 silver badges15 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

Well, it seems that you want to search for entire words, not strings.

Here's one approach that should suffice (although isn't fullproof).

Split the string into tokens based on whitespace or punctuation, this should give you a list of words (with some possible empty strings).

Now, if you want to check if your desired word exists in this list of words, you can use the includes method on the list.

console.log(
  "This is a pencil."
    .split(/\s+|\./) // split words based on whitespace or a '.'
    .includes('is')  // check if words exists in the list of words
)

If you want to count occurrences of a particular word, you can filter this list for the word you need. Now you just take the length of this list and you'll get the count.

console.log(
  "This is a pencil."
    .split(/\s+|\./) // split words based on whitespace or a '.'
    .filter(word => word === 'is')
    .length
)

This approach should also handle words at the beginning or the end of the string.

console.log(
  "This is a pencil."
    .split(/\s+|\./) // split words based on whitespace or a '.'
    .filter(word => word === 'This')
    .length
)

Alternatively, you could also reduce the list of words into the number of occurences

console.log(
  "This is a pencil."
    .split(/\s+|\./) // split words based on whitespace or a '.'
    .reduce((count, word) => word === 'is' ? count + 1 : count, 0)
)

search() takes a regex, so you can search for is surrounded by spaces

alert(str.search(/\sis\s/))

You can still use your .search() or .indexOf() to find the words. When looking for "is" in the "This is a pencil." example just do a str.search(" is ") (note the space before and after the word).

发布评论

评论列表(0)

  1. 暂无评论