remove special characters javascript

Remove special characters from a string using javascript

In this blog, we are going to learn different ways to remove special characters from a string in javascript.

We are going to use different regex expressions to remove special characters.

Negating alphabets and numbers

// String with special characters

let string = "@$@***Code*** Indoor***@$@";

// Method 1:Negating Alphabets and number

const method1 = string.replace(/[^a-zA-Z]/g, "");

// Output
// CodeIndoor

In the above example, we are using the expression in which we replace the non-alphabets and non-numbers with an empty string.

Removing specific special characters

// String with special characters

let string = "@$@***Code*** Indoor***@$@";

// Method 2:Removing specific special characters

const method2 = string.replace(/[<>{}#,+()$~*&/?]/g, "");

// Output
// @@Code Indoor@@

If we want to remove the specific special characters from the string, we will use the regex code mentioned above. In this expression, we need to add the special characters which should be removed from the string.

Negating Words

// String with special characters

let string = "@$@***Code*** Indoor***@$@";

// Method 3:Negating Words

const method3 = string.replace(/[^w]/g, "");

// Output
// CodeIndoor

In this example, we are replacing the non-words with empty strings so that special characters are removed from the string.

Remove special characters except white space

// String with special characters

let string = "@$@***Code*** Indoor***@$@";

// Method 4:Remove special characters except white space

const method4 = string.replace(/[^a-zA-Z ]/g, "");

// Output
// Code Indoor

If we want to remove all special characters except whitespace. Then we will use the above code, in which we are negating white space as well, so all the special characters other than white space are removed.

So, Using the above examples we can easily remove any special characters in the string.

Leave a Comment

Your email address will not be published. Required fields are marked *