Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Strip All Punctuation from a String in JavaScript Using Regex?”

This is very helpful! I think, however, there might be a problem with this:
/s{2,}/g
This would match an ‘s’ character, not whitespace characters. To match whitespace characters (space, newline, tab), you would need to use
/\s{2,}/g

Leave a Reply

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