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
Filter is a proper way to achieve that.
'this is my string'.split('').filter(s => s === 's').length
You can use split to do this:
myString = " this is my string ";
console.log(myString.split('s').length - 1);
You can use reduce to get info of all chars:
function countRepeatedChars(str) {
return str.split('').reduce((acc, val) => {
acc[val] = acc[val] ? ++acc[val] : 1
return acc
}, {})
}
console.log(countRepeatedChars('dfgdfghdfghdfhdfhwefw'))