Finding count of special characters in a string in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say that we have a string that may contain any of the following characters.

'!', "," ,"\'" ,";" ,"\"", ".", "-" ,"?"

We are required to write a JavaScript function that takes in a string and count the number of appearances of these characters in the string and return that count.

Example

The code for this will be −

const str = "This, is a-sentence;.Is this a sentence?";
const countSpecial = str => {
   const punct = "!,\;\.-?";
   let count = 0;
   for(let i = 0; i < str.length; i++){
      if(!punct.includes(str[i])){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countSpecial(str));

Output

The output in the console −

5
raja
Published on 15-Oct-2020 09:23:05
Advertisements