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

前端 未结 4 660
礼貌的吻别
礼貌的吻别 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:40

    Both answers posted so far left out the question mark. I would comment on them, but don't have enough rep yet.

    David is correct, sachleen's regex will leave underscores behind. rcdmk's regex, modified as follows, will do the trick, although if you care about international characters things might get a lot more complicated.

    var result = text.replace(/[^a-zA-Z0-9\s!?]+/g, '');
    

    This will leave behind new lines and tabs as well as spaces. If you want to get rid of new lines and tabs as well, change it to:

    var result = text.replace(/[^a-zA-Z0-9 !?]+/g, '');
    

提交回复
热议问题