How to Strip All Punctuation from a String in JavaScript Using Regex?

Sometimes, we want to strip all punctuation from a JavaScript string with a regex.

In this article, we’ll look at how to strip all punctuation from a JavaScript string with regex.

Use the String.prototype.replace Method

We can use the JavaScript string replace method to get all the parts of a string matching a regex pattern and replace them with what we want.

For instance, we can write:

const s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
const punctuationless = s
  .replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "")
  .replace(/\s{2,}/g, " ");
console.log(punctuationless)

We have the s string with lots of punctuation marks we want to remove.

Next, we call replace the first time with a regex that has all the punctuation marks that we want to remove inside.

The g flag indicates we match all instances in the string that matches the given pattern.

And we replace them all with an empty string as we indicate with the 2nd argument.

Then we call replace again with a regex that matches 2 or more whitespaces.

And we replace those whitespaces with one whitespace.

Therefore, punctuationless should be ‘This is an example of a string with punctuation’ .

Conclusion

We can use the JavaScript string replace method with a regex that matches the patterns in a string that we want to replace.

So we can use it to remove punctuation by matching the punctuation and replacing them all with empty strings.