How can I remove all characters from a string that are not letters using a JavaScript RegEx?
views:
516answers:
1
+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
2009-06-19 00:17:18
Just checked it in the console and it worked great. I wonder if he wanted to keep spaces.
Nosredna
2009-06-19 00:19:38