- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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';
Example
Let's write the code for this −
const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3'; const sumStringNum = str => { const strArr = str.split(""); let res = 0; for(let i = 0; i < strArr.length; i++){ if(+strArr[i]){ res += +strArr[i]; }; }; return res; }; console.log(sumStringNum(str));
Output
The output in the console −
35
Advertisements