
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Special Characters in a String Using 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
Advertisements