如何从字符串中删除除字母,数字,空格,感叹号和问号之外的所有内容? [英] How to remove everything but letters, numbers, space, exclamation and question mark from string?

查看:172
本文介绍了如何从字符串中删除除字母,数字,空格,感叹号和问号之外的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除所有内容,但:

How to remove everything but:

字符串中的字母,数字,空格,感叹号和问号?

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

该方法必须支持国际语言(UTF-8),这一点很重要.

It's important that the method supports international languages (UTF-8).

推荐答案

您可以使用正则表达式

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

这将替换单词,空格,感叹号或问题以外的所有内容.

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

字符类:\w代表文字字符",通常.请注意,其中包含下划线和数字.

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

\s代表空白字符".它包括[ \t\r\n].

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

如果您不想使用下划线,则可以只使用[A-Za-z0-9].

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

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

对于unicode字符,可以在表达式中添加类似\u0000-\u0080的内容.这将排除该unicode范围内的所有字符.您必须指定要不要删除的字符的范围.您可以在 Unicode映射上查看所有代码.只需添加要保留的字符或一系列字符即可.

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.

例如:

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

这将允许所有前面提到的字符,范围从\u0000-\u0080\u0082.它将删除\u0081.

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

这篇关于如何从字符串中删除除字母,数字,空格,感叹号和问号之外的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆