Remove special Characters from a String in JavaScript

Javascript remove special character from string example code; In this post we discuss how to remove Special Characters from a String in JavaScript.

In Js we can use the replace() method to remove all special characters from a string. The replace method will return a new string that doesn’t contain any special characters.

const str = 'hello !@#$%^WORLD?.';

const noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, '');
console.log(noSpecialCharacters); // 'hello WORLD'

We could also shorten the regular expression by using the \w character.

const str = 'hello !@#$%^WORLD?._';

const noSpecialCharacters = str.replace(/[^\w ]/g, '');
console.log(noSpecialCharacters); // 'hello WORLD_'

Note that the String.replace method does not change the original string. Instead, the method returns a new string with the matches replaced.