The Wayback Machine - https://web.archive.org/web/20240830063933/https://www.geeksforgeeks.org/javascript-program-to-remove-non-alphanumeric-characters-from-a-string/
Open In App

JavaScript Program to Remove Non-Alphanumeric Characters from a String

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Approach 1: Using Regular Expressions

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);

Output
HelloThisis123ateststring

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);

Output
HelloThisis123ateststring

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); 

Output
HelloThisis123ateststring

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

Output
HelloThisis123ateststring

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

Output
HelloThisis123ateststring

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

Output
HelloThisis123ateststring

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"

Output
HelloWorld123




Similar Reads

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 : GeeksforGeeks2018 Input : Geeks For Geeks Output
2 min read
How to validate if input in input field has alphanumeric characters only using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only alphanumeric characters are allowed i.e. there not allowed any special characters. We can also vali
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 regExUsing ASCII values with the Array filter methodApproa
3 min read
How to validate an input is alphanumeric or not using JavaScript ?
Given an input element and the task is to check whether the input element is alphanumeric or not. There are two methods to solve this problem which are discussed below: Approach 1: A RegExp is used to validate the input. RegExp is used to check the string of invalid characters which doesn't contain (a-z) alphabets and all numeric digits to validate
2 min read
JavaScript Program to Remove First and Last Characters from a String
This article will show you how to remove the first and last characters from a given string in JavaScript. There are two methods to remove the first and last characters in a string. Table of Content 1. Using String slice() Method2. Using String substring() Method3. Using Array Methods4. Using String substr() Method:5. Using Regular Expression and St
4 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 removedTable of Content Using Iterative LoopUsing Regula
5 min read
JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensuring all characters are the same. Given a string c
3 min read
PHP | ctype_alnum() (Check for Alphanumeric)
A ctype_alnum() function in PHP used to check all characters of given string/text are alphanumeric or not. If all characters are alphanumeric then return TRUE, otherwise return FALSE. Syntax: bool ctype_alnum ($text) Parameters Used: $text : It is a mandatory parameter which specifies the string. Examples: Input : Geeks Output : Yes Explanation : S
2 min read
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:Table of Content Methods to Strip all Non-Numeric Characters from String:Method 1: Using JavaScript replace() FunctionMethod 3: Usin
3 min read
JavaScript Program to Get a Non-Repeating Character From the Given String
In JavaScript, we can find the non-repeating character from the input string by identifying the characters that occur only once in the string. There are several approaches in JavaScript to get a non-repeating character from the given string which are as follows: Table of Content Using indexOf and lastIndexOf methodsUsing Set and Array.from()Using M
3 min read
JavaScript Program to Find K’th Non-Repeating Character in String
The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps identify the K'th non-repeating character in the
7 min read
Smallest Window in a String Containing all the Characters of Another String using JavaScript
Given two strings, "str" (the larger string) and "pattern" (the smaller string), the task is to find the smallest window in "str" that contains all the characters of "pattern" in any order using JavaScript. Examples: Input: str = "ADOBECODEBANC"pattern = "ABC"Output: BANCInput: str = "this is a test string"pattern = "tist";Output: t striTable of Co
3 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 print the string without vowels. Examples: Input :
2 min read
Javascript Program To Remove Duplicates From A Given String
Write a javascript program for a given string S which may contain lowercase and uppercase characters. The task is to remove all duplicate characters from the string and find the resultant string. Note: The order of remaining characters in the output should be the same as in the original string.Example: Input: Str = geeksforgeeksOutput: geksforExpla
3 min read
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 : Geeksforgeek Below are the following approaches th
3 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
JavaScript Program to Replace Characters of a String
Given a String the task is to replace characters of String with a given String in JavaScript. Examples: Input: Str = Welcome to GfG strRepl = GfG newStr = GeeksOutput: Welcome to GeeksTable of Content Using map() &amp; split() method to replace characters from StringUsing String replace() Method to replace characters from StringUsing Regular Expres
3 min read
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = “geeksforgeeks”Output:e, count = 4g, count = 2k, count = 2s, count = 2Table of Content Using For Loop in JavaScriptUsing S
5 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 : str = GeeksforGeeksOutput :Character at index 0:
4 min read
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same pattern according to the pattern given. Example: To so
4 min read
JavaScript Program to Swap Characters in a String
In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsing String ConcatenationUsing Regular ExpressionsUsi
6 min read
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a", ec = "a"Output: YesInput: str = "geekfor geeks",
3 min read
JavaScript Program to Check for Repeated Characters in a String
In this article, we are going to see various methods with which you can detect repeated characters in a string. Checking for repeated characters in a string involves examining the string's content to identify if any character occurs more than once. This helps detect duplications or repetitions within the text. Input: Str = “geeksforgeeks”Output:e,
6 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 accomplish this, such as utilizing loops and maps.
6 min read
JavaScript Program to Check if a String Contains Any Digit Characters
In this article, we will see how to check if a string contains any digit characters in JavaScript. Checking if a string contains any digit characters (0-9) in JavaScript is a common task when we need to validate user input or perform specific actions based on the presence of digits in a string. We will explore every approach to check if a string co
5 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 numeric values or not. If the string contains all of
4 min read
JavaScript Program to Replace Multiple Characters in a String
We are going to learn how we can replace Multiple Characters in a String. We have to replace multiple characters in a string using the inbuilt function or any other method. Table of Content Using replace() methodUsing replaceAll() methodUsing split() and join()Using regular expression Using reduce()Using Map for ReplacementUsing Object for Characte
5 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 : abdhijnpquvxyzInput : The quick brown fox jumpsO
7 min read
JavaScript Program to Check if a String Contains only Alphabetic Characters
We will check if a string contains only alphabetic characters in JavaScript. We will verify that all characters within the string are letters of the alphabet (A-Z or a-z) and do not include any digits, symbols, or other non-alphabetic characters. Below are the approaches to check if a string contains only alphabetic characters in JavaScript: Table
4 min read
Javascript Program to Count rotations required to sort given array in non-increasing order
Given an array arr[] consisting of N integers, the task is to sort the array in non-increasing order by minimum number of anti-clockwise rotations. If it is not possible to sort the array, then print "-1". Otherwise, print the count of rotations. Examples: Input: arr[] = {2, 1, 5, 4, 3}Output: 2Explanation: Two anti-clockwise rotations are required
3 min read