Hello I was wondering if anybody could help, i'm trying to search a string for a word and console log the amount of times that word appears in the string, however I only want it to return the count of whole words it finds, so at the moment the example below will return '3' because it will find 'car' twice but also the word 'care' which contains the word 'car' within it, is there anyway I can amend the code so it only finds the whole word and not words it's inside?
Many thanks.
<div class="sentence">I have a car and I need to take good care of this car</div>
let find = 'car';
let count = $('.sentence').text().split(find).length - 1;
console.log(count);
You can use regex and use test
to match the exact string. $('.sentence').text().split(' ')
will split the string and will create an array, then use reduce
to get the count. Inside reduce
callback use test to match exact word and if matches then increase the count
let find = 'car'; let count = $('.sentence').text().split(' ').reduce((acc, curr) => { if (/^car$/.test(curr)) { acc += 1; } return acc; }, 0) console.log(count);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sentence">I have a car and I need to take good care of this car</div>
Absolutely there is a way, use match:
let count = $('.sentence').text().match(/\bcar\b/g).length;
By using the word boundary ( \b
) the return is 2. Without using it (ie /car/
) the return would be 3 because of the word care in that string.
You can use match here to find all of the substrings.
const matches = line.match(/\bcar\b/g)
It returns null
if there are no matches or array with them
So, to count them:
const count = matches ? matches.length : 0
What you can do is split the word based on the space delimiter, which will return an array of words. You can then loop on this array and look for an exact match of your word:
const str = 'I have a car and I need to take good care of this car';
const words = str.split(' ');
words.forEach(function(word){
if (word==="car"){
console.log("found car")
}
})
Edit: Please note that if your sentence contains commas or other punctuation marks, you will need to split on those marks too.
let string = $('.sentence').text();
Now match the string which you are looking for. To find the exact match you can write like below
let count = string.match(/\bcar\b/g);
count = count? count.length : 0;
console.log(count);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.