Sometimes, we want to strip all punctuation from a string in JavaScript using regex.
In this article, we’ll look at how to strip all punctuation from a string in JavaScript using regex.
How to strip all punctuation from a string in JavaScript using regex?
To strip all punctuation from a string in JavaScript using regex, we call replace
with a regex to replace all the punctuation marks from a string.
For instance, we write
const newStr = str.replace(/[^\w\s]|_/g, "").replace(/\s+/g, " ");
to call replace
with /[^\w\s]|_/g
to match all instances of non word characters and spaces and replace them with empty strings.
And we call replace
again to replace all whitespaces with empty strings.
replace
returns the string with the replacement done.
Conclusion
To strip all punctuation from a string in JavaScript using regex, we call replace
with a regex to replace all the punctuation marks from a string.