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

前端 未结 4 595
礼貌的吻别
礼貌的吻别 2021-02-07 01:08

How to remove everything but:

letters, numbers, spaces, exclamation marks, question marks from a string?

It\'s important that the method supports international l

4条回答
  •  太阳男子
    2021-02-07 01:34

    You can use regex

    myString.replace(/[^\w\s!?]/g,'');
    

    This will replace everything but a word character, space, exclamation mark, or question.

    Character Class: \w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

    \s stands for "whitespace character". It includes [ \t\r\n].

    If you don't want the underscore, you can use just [A-Za-z0-9].

    myString.replace(/[^A-Za-z0-9\s!?]/g,'');
    

    For unicode characters, you can add something like \u0000-\u0080 to the expression. That will exclude all characters within that unicode range. You'll have to specify the range for the characters you don't want removed. You can see all the codes on Unicode Map. Just add in the characters you want kept or a range of characters.

    For example:

    myString.replace(/[^A-Za-z0-9\s!?\u0000-\u0080\u0082]/g,'');
    

    This will allow all the previously mentioned characters, the range from \u0000-\u0080 and \u0082. It will remove \u0081.

提交回复
热议问题