How to use ‘reduce’ Method In Javascript

In this method, we will use the reduce method to iterate through each character of the string and build a new string containing only numeric characters.

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

JavaScript
// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);

// Function to strip numeric characters
// and display output
function stripValues() {
    let nonNumericStr = str.split("").reduce((acc, char) => {
        return isNaN(char) || char === " " ? acc + char : acc;
    }, "");
    console.log(nonNumericStr);
}

// Function call
stripValues();

Output
1Gee2ksFor345Geeks6
w3wiki






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.

Similar Reads

Methods to Strip all Non-Numeric Characters from String:

Table of Content Methods to Strip all Non-Numeric Characters from String:Method 1: Using JavaScript replace() FunctionMethod 3: Using JavaScript str.split() and array.filter() methodsMethod 4: Using JavaScript ‘reduce’ Method...

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....

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

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

Method 4: Using JavaScript ‘reduce’ Method

In this method, we will use the reduce method to iterate through each character of the string and build a new string containing only numeric characters....