你好,我想知道是否有人可以帮助我,我试图搜索一个字符串中的一个词,并控制台记录该词在字符串中出现的次数,但是我只想让它返回它找到的整个单词的数量,所以目前下面的例子将返回'3',因为它会找到'car'两次,但也会找到'care'这个词,其中包含'car'这个词,有什么办法,我可以修改代码,使它只找到整个单词,而不是它里面的单词?
非常感谢。
<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);
你可以使用regex和使用 test
来匹配精确的字符串。$('.sentence').text().split(' ')
将拆分该字符串并创建一个数组,然后用 reduce
以获得数。内 reduce
回调使用 检验 匹配精确的单词,如果匹配则增加计数。
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>
绝对是有办法的,用匹配。
let count = $('.sentence').text().match(/\bcar\b/g).length;
用边界这个词\b
)的返回值是2,如果不使用它(即 /car/
)返回的结果将是3,因为该字符串中的单词照顾。
你可以做的是根据空格分隔符来分割单词,这将返回一个单词数组。然后你可以在这个数组上循环,寻找与你的词完全匹配的词。
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")
}
})
编辑:请注意,如果你的句子中包含逗号或其他标点符号,你也需要对这些符号进行分割。
你可以在这里使用 match 来查找所有的子串。
const matches = line.match(/\bcar\b/g)
它返回 null
如果没有匹配的对象或数组
所以,要计算它们。
const count = matches ? matches.length : 0
let string = $('.sentence').text();
现在匹配你要找的字符串。为了找到准确的匹配,你可以写下下面的内容
let count = string.match(/\bcar\b/g);
count = count? count.length : 0;
console.log(count);