且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从字符串中删除除字母,数字,空格,感叹号和问号之外的所有内容?

更新时间:2023-02-19 20:09:21

您可以使用正则表达式

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.