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
Summing numbers from a string - JavaScript
We are required to write a JavaScript function that takes in a string that contains some one-digit numbers in between and the function should return the sum of all the numbers present in the string.
Let's say the following is our string with numbers:
const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';
Method 1: Using for Loop with Type Conversion
This approach splits the string into characters and checks each one using type conversion:
const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';
const sumStringNum = str => {
const strArr = str.split("");
let res = 0;
for(let i = 0; i
35
Method 2: Using Regular Expression
A more concise approach using regex to extract all digits and sum them:
const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';
const sumStringNumRegex = str => {
const digits = str.match(/\d/g);
return digits ? digits.reduce((sum, digit) => sum + parseInt(digit), 0) : 0;
};
console.log(sumStringNumRegex(str));
35
Method 3: Using isNaN() Check
This method explicitly checks if each character is a number using isNaN():
const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';
const sumStringNumIsNaN = str => {
let sum = 0;
for(let char of str){
if(!isNaN(char) && char !== ' '){
sum += parseInt(char);
}
}
return sum;
};
console.log(sumStringNumIsNaN(str));
35
Comparison
| Method | Performance | Readability | Handles Edge Cases |
|---|---|---|---|
| Type Conversion (+) | Fast | Good | Limited |
| Regular Expression | Medium | Excellent | Best |
| isNaN() Check | Fast | Good | Good |
How It Works
All methods iterate through the string characters. The first method uses JavaScript's type coercion where +strArr[i] converts the character to a number (0 for non-digits, which is falsy). The regex method extracts all digits at once, while isNaN() explicitly validates numeric characters.
Conclusion
The regular expression method is most robust for extracting and summing digits from strings. For simple cases, the type conversion approach works well and is slightly more performant.
