How to remove special characters from string in jQuery or JavaScript?

How to remove special characters from string in jQuery or JavaScript?

Hello Guys,

Today, we are going to learn how to remove special characters from string in jQuery or JavaScript? In this tutorial, you will learn how to remove special character from string in JS or jQuery. I will show you few example on how to remove special character from string? We will use replace() method with some regex expressions to remove special characters from string.

So, let's get started. 

Example 1

If you wanna completely ignore the special characters you can use this example. We will use replace() method in examples but the regex expression will be change. Let's see the following example:

$(document).ready(function () {

  myString = "Hi, $%#Coders Vibe@@@";

  newString = myString.replace(/[^\w\s]/gi, '');

  console.log(newString);

});

Output

Hi Coders Vibe

 

Example 2

If you want to skip any special character then you can use this example. In this example we can skip any special character to being ignore with regex expression. Let's see following example:

$(document).ready(function () {

  myString = "Hi, $%#Coders Vibe @@@";

  newString = myString.replace(/[^a-zA-Z0-9@ ]/gi, '');

  console.log(newString);

});

Output

Hi Coders Vibe@@@

 

Conclusion

In the first example we are ignoring all special characters but in the last example we are allowing characters which are required so, we have update this /[^a-zA-Z0-9]/gi expression to skip the special characters like this /[^a-zA-Z0-9@]/gi

I hope it will help you.

Happy Coding :)

Leave a Comment

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

Go To Top
×