Remove Special Characters from a String in JavaScript

Share this Article
Reading Time: 4 minutes
695 Views

Inside this article we will see the concept i.e Remove special Characters from a String in JavaScript. Article contains the classified information about removing special characters from string values by using javascript regular expressions and/or methods. Tutorial is super easy to understand and implement it in your code as well.

If you are looking for a solution to remove special Characters from a String in JavaScript then this article will help you a lot for this.

Removing special characters from user input values before sending to database is very common client side validation that every web developer must apply to secure application.

Learn More –

Let’s get started.

Remove Special Characters From String

Create index.html file in your localhost path. Open file and add this code into it.

//...

<script>

  var str = 'Hello !@#$%^Online &&Web *& Tutor?.';

  var noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, '');

  console.log(noSpecialCharacters);

</script>

//...

Concept

Here,

To remove special characters from string values, we used regular expression.

var noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, '');

This regular expression will remove all special characters which are not in the given set. This given set contains characters from a-z, A-Z, 0-9 and space.

Output

Alternative Method

Also, we have an alternative way to do this special characters replacement. We use a known regular expression i.e [^\w ]

The above regular expression auto generates the set of a-z, A-Z, 0-9, _ and space.

Open index.html and add this code.

//...

<script>

  var str = 'Hello !@#$%^Online &&Web *& Tutor?.';

  var noSpecialCharacters = str.replace(/[^\w ]/g, '');

  console.log(noSpecialCharacters);

</script>

//...

Concept

var noSpecialCharacters = str.replace(/[^\w ]/g, '');

Output

We hope this article helped you to learn Remove special Characters from a String in JavaScript in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5