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