Non-alphanumeric characters in JavaScript are symbols and special characters that are not letters (a-z) or numbers (0-9). They include characters like @
, #
, $
, %
, and punctuation marks such as !
, ?
, and -
. These characters are not part of the alphabet or numeric system.
This pithy, example-based article will walk you through 3 different ways to eliminate all non-alphanumeric characters from a given string in modern JavaScript.
Using regular expressions
This solution uses a regular expression pattern with the replace()
method to remove all non-alphanumeric characters from the string. Here’s the pattern:
/[^a-z0-9]/gi
The approach is super concise. You can get the job done with a one-line code style:
input = "Welcome @-_+- to #$Sling Academy!"
output = input.replace(/[^a-z0-9]+/gi, '');
console.log(output)
Output:
WelcometoSlingAcademy
You can also define a function for reusability:
const removeNonAlphanumeric1 = (str) => {
return str.replace(/[^a-z0-9]+/gi, '');
};
Using a loop and a character set
If you don’t like regular expressions and feel uncomfortable about them, this is the way to go. The main idea here is to use a loop to iterate over every character in the string and check if it belongs to a predefined set of alphanumeric characters (you can easily add or remove some characters to or from this set as needed). If it does, it appends it to a new string. Otherwise, it ignores it.
Code example:
const removeNonAlphanumeric = (str) => {
// Define a set of alphanumeric characters as a string
let alphanum =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// Initialize an empty string to store the result
let result = '';
// Use a loop to iterate over every character in the input string
for (let i = 0; i < str.length; i++) {
// Check if the current character belongs to the alphanumeric set using the includes method
if (alphanum.includes(str[i])) {
// Append it to the result string using the += operator
result += str[i];
}
// Otherwise, ignore it and continue with the next iteration
}
// Return the result string as the output
return result;
};
// Test the function
let test = 'Welcome to Sling Academy! My name is @!#$%%[]{}-+*~`|\\<>,.?/';
console.log(removeNonAlphanumeric(test));
Output:
WelcometoSlingAcademyMynameis
This approach is more verbose than using regular expressions, but it is intuitive and easy to tweak.
Using a loop and ASCII range comparison
The main points of this approach can be described like this:
- Iterate over each character in the string.
- Use the
charCodeAt()
method to get the ASCII value of each character. - Check if the ASCII value falls within the alphanumeric range (between
48-57
,65-90
,97-122
). - Concatenate the valid characters to form the cleaned string.
Code example:
const removeNonAlphanumeric2 = (str) => {
let cleanedString = '';
for (let i = 0; i < str.length; i++) {
const charCode = str[i].charCodeAt();
if (
(charCode >= 48 && charCode <= 57) ||
(charCode >= 65 && charCode <= 90) ||
(charCode >= 97 && charCode <= 122)
) {
cleanedString += str[i];
}
}
return cleanedString;
};
// Example usage
const inputString = 'A@b#$%cd*&)}|]\\+=+=<>?/.,;:DEFDLKFDLKFLDFK22-3-443';
const cleanedString = removeNonAlphanumeric2(inputString);
console.log(cleanedString);
Output:
AbcdDEFDLKFDLKFLDFK223443
That’s it. Happy coding & have a nice day!