
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding count of special characters in a string in JavaScript
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
- Related Questions & Answers
- Finding special array - JavaScript
- Finding special type of numbers - JavaScript
- Finding special kind of sentences (smooth) in JavaScript
- Replacing all special characters with their ASCII value in a string - JavaScript
- Count special palindromes in a String in C++
- Search a string with special characters in a MongoDB document?
- How to count special characters in an R vector?
- Finding number of alphabets, digits and special characters in strings using C language
- Check if string contains special characters in Swift
- Write a Regular Expression to remove all special characters from a JavaScript String?
- Regrouping characters of a string in JavaScript
- Special Characters in HTML
- Finding special kind of elements with in an array in JavaScript
- Finding number of spaces in a string JavaScript
- Finding mistakes in a string - JavaScript
Advertisements