Thursday, July 4, 2024
HomeLanguagesJavascriptJavaScript Strip all non-numeric characters from string

JavaScript Strip all non-numeric characters from string

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 = /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();


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

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments