Open In App
Related Articles

JavaScript Strip all non-numeric characters from string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will strip all non-numeric characters from a string. In order to remove all non-numeric characters from a string, replace() function is used.

Methods to Strip all Non-Numeric Characters from String:

Method 1: Using JavaScript replace() Function

This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

Syntax:

string.replace( searchVal, newValue )

Example 1: This example strips all non-numeric characters from the string ‘1Gee2ksFor345Geeks6’ with the help of RegExp.

Javascript

// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);
 
// Function to get non-numeric numbers
// and display output
function stripValues() {
    console.log(str.replace(/\D/g, ""));
}
 
// Function call
stripValues();

                    

Output
1Gee2ksFor345Geeks6
123456

Method 2: Using JavaScript Regular Expression and match method

regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations.

Syntax:

let patt = /GeeksforGeeks/i;

Example: This example strips all non-numeric characters from the string ‘1Gee2ksFor345.Gee67ks89’ with the help of RegExp. This example preserves the float numbers.

Javascript

// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);
 
// Function to get non-numeric numbers
// and display output
function stripValues() {
    console.log((str.match(/[^\d.-]/g,"") || []).join(""));
}
 
// Function call
stripValues();

                    

Output
1Gee2ksFor345Geeks6
GeeksForGeeks

Method 3: Using JavaScript str.split() and array.filter() methods

Example: In this example, we will use str.split() and array.filter() methods

Javascript

// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);
 
// Function to get non-numeric numbers
// and display output
function stripValues() {
    console.log( str.split("").filter(char => isNaN(parseInt(char))).join(""));
}
 
// Function call
stripValues();

                    

Output
1Gee2ksFor345Geeks6
GeeksForGeeks



Last Updated : 21 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads