How to remove all non-alphanumeric characters from the String? (w/wo space/hyphen/dashes)

Non-alphanumeric characters are those characters which are not alphabets or numbers.

For example characters like exclamation mark(!), commas(,), question mark(?), colon(:), semicolon (;) etc.

We will learn two ways to remove non- alphanumeric characters from a string. Both the methods are discussed below.

Remove all non-alphanumeric Characters from String (Including Spaces, Hyphen)

One way is to use an inbuilt function called ‘replace()’. This method helps to replace all the alphanumeric characters with an empty string based on the condition that we have added as a regex.

Regex & Syntax: str.replace(/[^a-z0-9]/gi, ”)

JavaScript Code:

const str = 'DummyStringA!@#b$%^c&*(';
const newString = str.replace(/[^a-z0-9]/gi, '');
console.log(newString); // DummyStringAbc



Remove all non-alphanumeric Characters from String (Including spaces and dashes/hyphens)

Regex & Syntax: str.replace(/[^a-z0-9]/gi, ”)

JavaScript Code:

const str = 'Dummy String - A!@# b$% ^c&*(';
const newString = str.replace(/[^a-z0-9 -]/gi, '');
console.log(newString); // Dummy String - A b c


// Spaces, Hyphens/Dashes are Preserved.

Dummy String - A b c


Here str is the name of the string and there are 2 arguments in replace function, the first one in which we provide the characters which we want to replace and the second is the empty string by which all the provided characters will get replaced and finally we will get the output as ‘DummyStringAbc’ & ‘Dummy String – A b c’.

Another method could be with the ASCII values matching.

The ASCII value of the alphanumeric characters lies between [65,90] for uppercase alphabets, [97,122] for the lowercase alphabets and [48,57] for the digits. So, what we can do is, we can traverse the string character by character and find out the ASCII value of each character. If the value lies in the three ranges stated above then the character is a non-alphanumeric character. The ASCII value that didn’t come under any of the three ranges we can skip such characters and add rest of the characters of the string and print it.

Leave a Comment