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:
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
let str = "1Gee2ksFor345Geeks6" ;
console.log(str);
function stripValues() {
console.log(str.replace(/\D/g, "" ));
}
stripValues();
|
Output
1Gee2ksFor345Geeks6
123456
Method 2: Using JavaScript Regular Expression and match method
A 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
let str = "1Gee2ksFor345Geeks6" ;
console.log(str);
function stripValues() {
console.log((str.match(/[^\d.-]/g, "" ) || []).join( "" ));
}
stripValues();
|
Output
1Gee2ksFor345Geeks6
GeeksForGeeks
Example: In this example, we will use str.split() and array.filter() methods
Javascript
let str = "1Gee2ksFor345Geeks6" ;
console.log(str);
function stripValues() {
console.log( str.split( "" ).filter(char => isNaN(parseInt(char))).join( "" ));
}
stripValues();
|
Output
1Gee2ksFor345Geeks6
GeeksForGeeks
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!