I’ve this piece of code that will count the number of occurrences found in a given string.
But it will only count the number of unique special characters in the string.
How can I change this behavior ?
It should give me 3 and not 1 as I have 3 spaces.
Thanks.
var string = 'hello, i am blue.';
var specialChar = [' ', '!'];
let count = 0
specialChar.forEach(word => {
string.includes(word) && count++
});
console.log(count);
>Solution :
What you are doing is iterating over specialChar, which yields two iterations: the first iteration will check if ' ' is included in the string which is true and thus increments count, and the second iteration will check if '!' is included in the string which is not the case hence you get 1.
What you should actually do is iterate through the string and check if each character is included in the specialChar array. Here is how you can do that with the minimum changes made (the code can be improved and made clearer).
Note: .split("") splits the string to an array of its characters.
var string = 'hello, i am blue.';
var specialChar = [' ', '!'];
let count = 0
string.split("").forEach(char => {
specialChar.includes(char) && count++
});
console.log(count);