How to usethe replace() Method with a Custom Function in Javascript
The replace() method can be used with a custom function that checks each character and replaces non-alphanumeric characters.
Syntax:
function removeNonAlphanumeric(inputString) {
return inputString.replace(/./g, char => {
if (/[a-zA-Z0-9]/.test(char)) {
return char;
}
return '';
});
}
Example: In this example we are using the above-explained approach.
function romveFunction(inputString) {
return inputString.replace(/./g, char => {
if (/[a-zA-Z0-9]/.test(char)) {
return char;
}
return '';
});
}
const originalString =
"Hello! This is 123 a test string.";
const result =
romveFunction(originalString);
console.log(result);
Output
HelloThisis123ateststring
JavaScript Program to Remove Non-Alphanumeric Characters from a String
We will see how to remove non-alphanumeric characters from a string in JavaScript. Non-alphanumeric characters are symbols, punctuation, and whitespace. Removing them from a string This task can be useful when you want to clean up user inputs, sanitize strings, or perform various text processing operations.
There are multiple approaches to removing non-alphanumeric characters from a string in JavaScript.
Table of Content
- Approach 1: Using Regular Expressions
- Approach 2: Using a Loop and Character Checking
- Approach 3: Using the replace() Method with a Custom Function
- Approach 4: Using Array Filter and Regular Expression
- Approach 5: Using the reduce() Method
- Approach 6: Using Array Map and Join
We will explore all the above methods along with their basic implementation with the help of examples.