views:

516

answers:

1

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

+15  A: 

You can use the replace method:

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

If you wanted to keep spaces:

'Hey! The #123 sure is fun!'.replace(/[^a-z\s]/gi, '');
>>> "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).

Paolo Bergantino
Just checked it in the console and it worked great. I wonder if he wanted to keep spaces.
Nosredna