I am trying to find the total number of a specific character is in string.
for example
myString = " this is my string ";
I want to count how many "s" is in myString. I tried the following:
function myFunction(a, b) {
const letters = b.split("");
console.log(letters);
letters.forEach(letter => {
let letterCount = 0;
if(letter === a) {
console.log("yes")
letterCount++;
}
console.log(letterCount);
})
}
myFunction('s', 'this is my string') // Expected result: 3
您可以使用reduce获取所有字符的信息:
<!-开始代码段:js hide:false控制台:true babel:false-->
<!-语言:lang js-->
function countRepeatedChars(str) {
return str.split('').reduce((acc, val) => {
acc[val] = acc[val] ? ++acc[val] : 1
return acc
}, {})
}
console.log(countRepeatedChars('dfgdfghdfghdfhdfhwefw'))
<!-结束代码段-->
Using a simple regular expression
function escapeRegExp(string) { // from https://stackoverflow.com/a/6969486/12101554
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
const myFunction = (match, str) => str.match(new RegExp(escapeRegExp(match), "g"))?.length ?? 0;
console.log(myFunction('s', 'this is my string')) // Expected result: 3
console.log(myFunction('s', 'thi i my tring')) // Expected result: 0
console.log(myFunction('a', 'john has five apples and six bananas')) // Expected result: 6
您可以使用拆分
执行以下操作:
<!-开始代码段:js hide:false控制台:true babel:false-->
<!-语言:lang js-->
myString = " this is my string ";
console.log(myString.split('s').length - 1);
<!-结束代码段-->
更简单的方法是使用regexp进行计数.
<!-开始代码段:js hide:false控制台:true babel:false-->
<!-语言:lang js-->
myString = " Sure this iss my string ";
console.log(myString.match(/(s)/ig).length);
<!-结束代码段-->
过滤器是实现这一点的正确方法.