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

Time:01-28

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);

CodePudding user response:

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);

CodePudding user response:

One way to count characters in a string is to split the string by the character and then count the parts and subtract one.

var string = 'hello! i am blue!';
var specialChar = [' ', '!'];

let count = 0
specialChar.forEach(char => {
  count  = string.split(char).length - 1
});

console.log(count);

Made into a function using reduce

function countChars(string, chars) {
    return chars.reduce(
      (acc, char) => acc   string.split(char).length - 1,
      0
    );
}

console.log(countChars('hello! i am blue!', [' ', '!']));

CodePudding user response:

Since you're using an array of matches [" ", "!"] you need as an output - and Object with the counts, i.e: {" ": 5, "!": 2}.

Here's two examples, one using String.prototype.match(), and the other using Spread Syntax ... on a String

Using Match

and Array.prototype.reduce() to reduce your initial Array to an Object result

const string = 'hello, i am blue. And this is an Exclamation! Actually, two!';
const specialChar = [' ', '!'];

const regEscape = v => v.replace(/[-[\]{}()* ?.,\\^$|#\s]/g, '\\$&');

const count = specialChar.reduce((ob, ch) => {
  ob[ch] = string.match(new RegExp(regEscape(ch), "g")).length;
  return ob; 
}, {}); // << This {} is the `ob` accumulator object

console.log(count);

Using String spread ...

to convert the string to an array of Unicode code-points sequences / symbols

const string = 'hello, i am blue. And this is an Exclamation! Actually, two!';
const specialChar = [' ', '!'];

const count = [...string].reduce((ob, ch) => {
  if (!specialChar.includes(ch)) return ob;
  ob[ch] ??= 0;
  ob[ch]  = 1;
  return ob; 
}, {}); // << This {} is the `ob` accumulator object

console.log(count);

  • Related