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 03 Answers
Reset to default 4Well, 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).
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744225516a4563984.html
评论列表(0条)