Hi Friends 👋,

Welcome To Infinitbility! ❤️

To remove special characters and space in javascript, just use replace() method with /[ `[email protected]#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g regex then it will return new string without special characters and spaces.

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If the pattern is a string, only the first occurrence will be replaced.

Let’s take an example to remove special characters and space using the replace() method.

const regex = /[ `[email protected]#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g;

var str = "Hi Frinds & Welcome to infinitbility";

str.replace(regex, '');
// 👇️ Output
//   "HiFrindsWelcometoinfinitbility"

Today, I’m going to show you How do I remove special characters and space in javascript, as above mentioned here, I’m going to use the replace() method with /[ `[email protected]#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g regex to delete special characters and space from a string.

Let’s start today’s tutorial how do you remove special characters and space in javascript?

In this example, we will do

  1. example of remove special characters and space
  2. example of replace special characters and space with an underscore ( _ )
  3. example of replace special characters and space with a hyphen ( - )
  4. example of replace special characters and space with an underscore ( _ ) with

Let’s write code…

javascript replace example

const regex = /[ `[email protected]#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g;

var str = "Hi Frinds & Welcome to é infinitbility";

// example of remove remove special characters and space
str.replace(regex, '');

// example of replace special characters and space with underscore ( _ )
str.replace(regex, '_');

// example of replace special characters and space with hyphen ( - )
str.replace(regex, '-');

As mentioned above, we are taken the example of a string variable, remove special characters and spaces from the string and print the output on the screen.

I hope it helps you, All the best 👍.

JavaScript, remove special characters and space example
JavaScript, remove special characters and space example