Here are two ways to remove all the non-alphanumeric characters from a string.
- Using string.replace() with regular expression
- Using for loop
Method 1: Using the str.replace() function
The str.replace() method is “used to search and replace specified substrings or patterns within a string.”
Syntax
str.replace();
Return value
This method returns a new string with all matches replaced.
Example
const str = 'jo@#*hn'
const replaced = str.replace(/[^a-z0-9]/gi, '');
console.log(replaced);
Output
john
Method 2: Using for loop
You can use a for loop to iterate through each character in a string and check if it’s alphanumeric. If it is, you can add it to a new string. This method is straightforward and can be used in many programming languages, including JavaScript.
Example
function removeNonAlphanumeric(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') ||
(str[i] >= 'A' && str[i] <= 'Z') ||
(str[i] >= '0' && str[i] <= '9')) {
result += str[i];
}
}
return result;
}
console.log(removeNonAlphanumeric("Hello, World!123"));
Output
HelloWorld123
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.