JavaScript Program to Remove Non-Alphanumeric Characters from a String
Last Updated :
10 Jul, 2024
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.
We will explore all the above methods along with their basic implementation with the help of examples.
Regular expressions offer a concise way to match and remove non-alphanumeric characters. We can use the replace() method with a regular expression to replace all non-alphanumeric characters with an empty string.
Syntax:
function removeNonAlphanumeric(inputString) {
return inputString.replace(/[^a-zA-Z0-9]/g, '');
};
Example: In this example we are using the above-explained approach.
JavaScript
function removeFunction(inputString) {
return inputString.replace(/[^a-zA-Z0-9]/g, '');
}
const originalString =
"Hello! This is 123 a test string.";
const result =
removeFunction(originalString);
console.log(result);
OutputHelloThisis123ateststring
Approach 2: Using a Loop and Character Checking
By iterating through each character in the string and checking if it's alphanumeric, we can construct the resulting string without non-alphanumeric characters.
Syntax:
for (let i = 0; i < inputString.length; i++) {
const char = inputString[i];
if (/[a-zA-Z0-9]/.test(char)) {
result += char;
}
};
Example: In this example we are using the above-explained approach.
JavaScript
function removeFunction(inputString) {
let result = '';
for (let i = 0; i < inputString.length; i++) {
const char = inputString[i];
if (/[a-zA-Z0-9]/.test(char)) {
result += char;
}
}
return result;
}
const originalString =
"Hello! This is 123 a test string.";
const result =
removeFunction(originalString);
console.log(result);
OutputHelloThisis123ateststring
Approach 3: Using the replace() Method with a Custom Function
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.
JavaScript
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);
OutputHelloThisis123ateststring
Approach 4: Using Array Filter and Regular Expression
In this approach, we split the input string into an array of characters using split(''), then we use the filter() method along with a regular expression to filter out non-alphanumeric characters. Finally, we join the filtered array back into a string using join('').
Example:
JavaScript
function removeNonAlphanumeric(inputString) {
return inputString.split('').filter(char => /[a-zA-Z0-9]/.test(char)).join('');
}
const originalString = "Hello! This is 123 a test string.";
const result = removeNonAlphanumeric(originalString);
console.log(result); // Output: HelloThisis123ateststring
OutputHelloThisis123ateststring
Approach 5: Using the reduce() Method
The reduce() method can be used to iterate over each character in the string, accumulate only the alphanumeric characters, and construct the resulting string.
Example:
JavaScript
function removeFunction(inputString) {
return inputString.split('').reduce((acc, char) => {
return /[a-zA-Z0-9]/.test(char) ? acc + char : acc;
}, '');
}
const originalString = "Hello! This is 123 a test string.";
const result = removeFunction(originalString);
console.log(result); // Output: HelloThisis123ateststring
OutputHelloThisis123ateststring
Approach 6: Using Array Map and Join
In this approach, we split the input string into an array of characters using split(''), then we use the map() method to replace non-alphanumeric characters with an empty string. Finally, we join the transformed array back into a string using join('').
Example:
JavaScript
function removeNonAlphanumeric(inputString) {
return inputString.split('').map(char => {
return /[a-zA-Z0-9]/.test(char) ? char : '';
}).join('');
}
const originalString = "Hello! This is 123 a test string.";
const result = removeNonAlphanumeric(originalString);
console.log(result); // Output: HelloThisis123ateststring
OutputHelloThisis123ateststring
Approach 7: Using filter Method with String Conversion
In this approach, we convert the input string to an array of characters using Array.from(), then use the filter method to keep only alphanumeric characters. Finally, we convert the filtered array back into a string using join().
Example: This example demonstrates how to remove non-alphanumeric characters using the filter method and string conversion.
JavaScript
function removeNonAlphanumeric(inputString) {
return Array.from(inputString)
.filter(char => /[a-zA-Z0-9]/.test(char))
.join('');
}
// Example usage:
let inputString = "Hello, World! 123.";
let cleanedString = removeNonAlphanumeric(inputString);
console.log(cleanedString); // Output: "HelloWorld123"
Similar Reads
JavaScript Program to Remove Vowels from a String The task is to write a JavaScript program that takes a string as input and returns the same string with all vowels removed. This means any occurrence of 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase) should be eliminated from the string. Given a string, remove the vowels from the string and
2 min read
JavaScript - String Contains Only Alphabetic Characters or Not Here are several methods to check if a string contains only alphabetic characters in JavaScriptUsing Regular Expression (/^[A-Za-z]+$/) - Most USedThe most common approach is to use a regular expression to match only alphabetic characters (both uppercase and lowercase).JavaScriptlet s = "HelloWorld"
2 min read
JavaScript - Remove all Occurrences of a Character in JS String These are the following ways to remove all occurrence of a character from a given string: 1. Using Regular ExpressionUsing a regular expression, we create a pattern to match all occurrences of a specific character in a string and replace them with an empty string, effectively removing that character
2 min read
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and nu
4 min read
How to remove all Non-ASCII characters from the string using JavaScript ? In this article, we are given a string containing some non-ASCII characters and the task is to remove all non-ASCII characters from the given string. Approaches to remove all Non-ASCII Characters from String: Table of Content Using ASCII values in JavaScript regExUsing Unicode in JavaScript regExUsi
3 min read
How to remove non-alphanumeric characters in PHP? Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found. Examples: Input : !@GeeksforGeeks2018? Output
2 min read
JavaScript - Strip All Non-Numeric Characters From String Here are the different methods to strip all non-numeric characters from the string.1. Using replace() Method (Most Common)The replace() method with a regular expression is the most popular and efficient way to strip all non-numeric characters from a string.JavaScriptconst s1 = "abc123xyz456"; const
2 min read
Remove a Character From String in JavaScript In JavaScript, a string is a group of characters. Strings are commonly used to store and manipulate text data in JavaScript programs, and removing certain characters is often needed for tasks like:Removing unwanted symbols or spaces.Keeping only the necessary characters.Formatting the text.Methods t
3 min read
Program for removing i-th character from a string Given a string S along with an integer i. Then your task is to remove ith character from S. Examples: Input: S = Hello World!, i = 7Output: Hello orld!Explanation: The Xth character is W and after removing it S becomes Hello orld! Input: S = GFG, i = 1Output: GGExplanation: It can be verified that a
5 min read
Java Program to Replace Multiple Characters in a String In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
3 min read