How to remove all characters from a string

后端 未结 3 941
北荒
北荒 2020-12-16 02:15

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

3条回答
  •  死守一世寂寞
    2020-12-16 02:54

    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).

提交回复
热议问题