Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In JS, count the number of occurence found in a string

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading