JavaScript - Strip All Non-Numeric Characters From String
Here are the different methods to strip all non-numeric characters from the string.
1. Using replace() Method (Most Common)
The replace() method with a regular expression is the most popular and efficient way to strip all non-numeric characters from a string.
const s1 = "abc123xyz456";
const s2 = s1.replace(/\D/g, "");
console.log(s2);
Output
123456
- \D matches any non-digit character.
- The g flag ensures global replacement.
2. Using split() and filter() Methods
This method splits the string into an array of characters, filters out non-numeric characters, and joins the result back into a string.
const s1 = "abc123xyz456";
const s2 = s1.split("").filter(char =>
!isNaN(char) && char !== " ").join("");
console.log(s2);
Output
123456
- split("") splits the string into individual characters.
- filter() checks if the character is numeric using !isNaN(char).
- join("") combines the numeric characters back into a string.
3. Using reduce() Method
The reduce() method can be used to accumulate only numeric characters into a result string.
const s1 = "abc123xyz456";
const s2 = s1.split("").reduce((acc, char) => {
return !isNaN(char) && char !== " " ? acc + char : acc;
}, "");
console.log(s2);
Output
123456
reduce() iterates through the characters, adding numeric ones to the accumulator.
4. Using forEach() Method
The forEach() method processes each character and adds numeric ones to a result string.
const s1 = "abc123xyz456";
let s2 = "";
s1.split("").forEach(char => {
if (!isNaN(char) && char !== " ") {
s2 += char;
}
});
console.log(s2);
Output
123456
forEach() iterates over the array of characters, selectively appending numeric ones.
5. Using a Naive Approach (Manual Loop)
A simple loop can iterate through the string and build a new string containing only numeric characters.
const s1 = "abc123xyz456";
let s2 = "";
for (const char of s1) {
if (!isNaN(char) && char !== " ") {
s2 += char;
}
}
console.log(s2);
Output
123456
- Suitable for beginners.
- Does not rely on higher-order functions or regular expressions.
Which Approach to Use?
Approach | When to Use |
---|---|
Using replace() | Best for simplicity and efficiency. Handles most cases easily. |
Using split() and filter() | Ideal for functional programming and readability. |
Using reduce() | Suitable for chaining operations or working with functional styles. |
Using forEach() | Best when combining logic with side effects. |
Naive Approach | Suitable for beginners and small-scale applications. |
For most use cases, replace() is the recommended approach due to its simplicity and performance. Other methods are better suited for specific requirements, like chaining operations or understanding functional programming techniques.