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 Last Character from the String
In this article, we will learn how to remove the last character from the string in JavaScript. The string is used to represent the sequence of characters. Now, we will remove the last character from this string. Example: Input : Geeks for geeks Output : Geeks for geek Input : Geeksforgeeks Output :
3 min read
JavaScript- Remove Last Characters from JS String
These are the following ways to remove first and last characters from a String: 1. Using String slice() MethodThe slice() method returns a part of a string by specifying the start and end indices. To remove the last character, we slice the string from the start (index 0) to the second-to-last charac
2 min read
JavaScript Program to Remove Consecutive Duplicate Characters From a String
We are going to implement a JavaScript program to remove consecutive duplicate characters from a string. In this program, we will eliminate all the consecutive occurrences of the same character from a string. Example: Input: string: "geeks" Output: "geks"Explanation :consecutive "e" should be remove
5 min read
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 JavaScript Using 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). [GFGTABS] JavaScript let s =
2 min read
JavaScript Program to Mirror Characters of a String
Our task is to mirror characters from the N-th position up to the end of a given string, where 'a' will be converted into 'z', 'b' into 'y', and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to
6 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 Access Individual Characters in a String
In this article, we are going to learn about accessing individual characters from the given string. Accessing individual characters in a string means retrieving a specific character from the string using its index position (zero-based) or iterating through each character one by one. Example: Input :
4 min read
JavaScript Program to Find Missing Characters to Make a String Pangram
We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeksOutput
7 min read
JavaScript - How to Replace Multiple Characters in a String?
Here are the various methods to replace multiple characters in a string in JavaScript. 1. Using replace() Method with Regular ExpressionThe replace() method with a regular expression is a simple and efficient way to replace multiple characters. [GFGTABS] JavaScript const s1 = "hello world!
3 min read