How to remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string?

Sometimes, we want to remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string.

In this article, we’ll look at how to remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string.

How to remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string?

To remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string, we can use the JavaScript string’s replace method.

For instance, we write:

const text = "A(B){C};:a.b*!c??!1<>2@#3"
const result = text.replace(/[^a-zA-Z0-9]/g, '')
console.log(result)

We call text.replace with a regex that matches all characters that aren’t letters and numbers and replace them with empty strings.

As a result, result is 'ABCabc123'.

Conclusion

To remove everything but letters, numbers, space, exclamation and question mark from a JavaScript string, we can use the JavaScript string’s replace method.