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
Filtering out numerals from string in JavaScript
Problem
We are required to write a JavaScript function that takes in a string, str, which contains a combination of alphabets, special characters and numbers.
Our function should return a new string based on the input string that contains only the numbers present in the string str, maintaining their relative order.
For example, if the input to the function is −
const str = 'revd1fdfdfs2v34fd5gfgfd6gffg7ds';
Then the output should be −
const output = '1234567';
Example
Following is the code −
const str = 'revd1fdfdfs2v34fd5gfgfd6gffg7ds';
const pickNumbers = (str = '') => {
let res = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(+el){
res += el;
};
};
return res;
};
console.log(pickNumbers(str));
Output
Following is the console output −
1234567
Advertisements