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:
- Using JavaScript replace() Function
- Using JavaScript Regular Expression
- Using JavaScript str.split() and array.filter() methods
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(); |
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 = /neveropen/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(); |
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(); |
1Gee2ksFor345Geeks6 GeeksForGeeks