Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding count of special characters in a string in JavaScript
In JavaScript, you can count special characters in a string by checking each character against a predefined set of special characters. This is useful for text validation, content analysis, or data processing tasks.
Problem Statement
We need to count occurrences of these special characters in a string:
'!', ',', ''', ';', '"', '.', '-', '?'
The function should iterate through each character and increment a counter when it finds a match.
Example Implementation
const str = "This, is a-sentence;.Is this a sentence?";
const countSpecial = str => {
const punct = "!,';".-?";
let count = 0;
for(let i = 0; i
5
Alternative Approach Using Regular Expression
You can also use a regular expression for more concise code:
const str = "This, is a-sentence;.Is this a sentence?";
const countSpecialRegex = str => {
const specialChars = /[!,';".\-?]/g;
const matches = str.match(specialChars);
return matches ? matches.length : 0;
};
console.log(countSpecialRegex(str));
5
Method Comparison
| Method | Performance | Readability | Flexibility |
|---|---|---|---|
| Loop with includes() | Good | High | Easy to modify character set |
| Regular Expression | Very Good | Medium | Powerful pattern matching |
Testing with Different Inputs
// Test various cases
console.log(countSpecial("Hello World!")); // 1
console.log(countSpecial("No special chars")); // 0
console.log(countSpecial("!@#$%^&*()")); // 2 (only ! and - if present)
console.log(countSpecial("")); // 0
1 0 1 0
Conclusion
Both loop-based and regex approaches effectively count special characters. Choose the loop method for clarity or regex for performance and pattern flexibility.
Advertisements
