How to remove all characters from a string

javascript, regex, string

Solution

You can use the `replace` method:

'Hey! The #123 sure is fun!'.replace(/[^A-Za-z]+/g, '');
>>> "HeyThesureisfun"

If you wanted to keep spaces:

'Hey! The #123 sure is fun!'.replace(/[^A-Za-z\s]+/g, '');
>>> "Hey The sure is fun"

The regex `/[^a-z\s]/gi` is basically saying to match anything not the letter a-z or a space (\s), while doing this globally (the `g` flag) and ignoring the case of the string (the `i` flag).

Problem

How can I remove all characters from a string that are not letters using a JavaScript RegEx?

Original source