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
Count total punctuations in a string - JavaScript
In JavaScript, you can count punctuation marks in a string by checking each character against a set of punctuation symbols. Common punctuation marks include periods, commas, semicolons, exclamation marks, question marks, and quotation marks.
Common Punctuation Characters
'!', ",", "'", ";", '"', ".", "-", "?"
Example
Here's a JavaScript function that counts punctuation marks in a string:
const str = "This, is a-sentence;.Is this a sentence?";
const countPunctuation = str => {
const punct = "!,';".?-";
let count = 0;
for(let i = 0; i
String: This, is a-sentence;.Is this a sentence?
Punctuation count: 5
Using Array Methods
You can also use array methods for a more functional approach:
const countPunctuationArray = str => {
const punctuations = ["!", ",", "'", ";", '"', ".", "-", "?"];
return str.split('').filter(char => punctuations.includes(char)).length;
};
const testString = "Hello, world! How are you today?";
console.log("String:", testString);
console.log("Punctuation count:", countPunctuationArray(testString));
String: Hello, world! How are you today?
Punctuation count: 4
Using Regular Expressions
Regular expressions provide another efficient method:
const countPunctuationRegex = str => {
const punctuationPattern = /[!,';".\-?]/g;
const matches = str.match(punctuationPattern);
return matches ? matches.length : 0;
};
const sampleText = "It's amazing! Isn't it? Yes, indeed.";
console.log("String:", sampleText);
console.log("Punctuation count:", countPunctuationRegex(sampleText));
String: It's amazing! Isn't it? Yes, indeed.
Punctuation count: 6
Comparison
| Method | Performance | Readability | Flexibility |
|---|---|---|---|
| For Loop with includes() | Good | High | Medium |
| Array Methods | Medium | High | High |
| Regular Expressions | Best | Medium | High |
Conclusion
Use the for loop approach for simple cases, array methods for functional programming style, or regular expressions for complex punctuation patterns. Choose based on your specific requirements and performance needs.
Advertisements
