繁体   English   中英

Javascript删除字符串中不是数字,字母和空格的所有字符

[英]Javascript remove all characters from string which are not numbers, letters and whitespace

使用JavaScript我想删除字符串中不是数字,字母和空格的所有字符。 所以删除'%#$&@*等字符,如下所示:

玩家必须玩! #justsaying

会成为:

玩家必须玩得很开心

我怎么能这样做,我不确定正则表达式。

正如@ chris85所说,你可以使用正则表达式[^0-9a-zAZ]来替换所有不是字母,数字或空格的字符。

这是一个可以做你想要的功能:

function clean(str) {
    return str.replace(/[^0-9a-z-A-Z ]/g, "").replace(/ +/, " ")
}

需要第二次替换调用来删除通过删除空格之间的字符而产生的额外空格的运行。

使用replace

string.replace(/[^A-Z\d\s]/gi, '')

注意正则表达式末尾的两个标志

g - 代表全局,意味着将找到正则表达式的每个这样的实例

i - 代表不区分大小写。 这意味着它将匹配小写和大写字符

使用您的字符串,它返回此输出

"Players got to  play justsaying"

要将两个或多个空白字符转换为单个空格,您可以使用另一种replace现有方法。

string.replace(/[^A-Z\d\s]/gi, '').replace(/\s+/g, ' ')

这里的关键是+字符,它找到一个或多个。

可能更有效率地做到这一点,但我是Regex的业余爱好者。

原文

Player's got to * play! #justsaying

REGEXP

([^a-zA-Z0-9\s])

结果

Players got to  play justsaying

测试它

 const regex = /([^a-zA-Z0-9\\s])/gm; const str = `Player's got to * play! #justsaying`; const subst = ``; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log(result); 

请参阅: https //regex101.com/r/BYSDwz/4

我还为正则表达式添加了符号'因为你有单词Player's ,所以这里是我的代码:

var str = "Player's got to * play! #justsaying";
var result = str.replace(/[^a-z\d\s']/gi, '');

试试吧

var text = "Player's got to * play! #justsaying";
var result = text.replace(/[^A-Z\d\s]/gi,'');
console.log(result);

阅读更多内容: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

这就是你如何匹配你有兴趣删除的角色......

[^\d\w\s]

注意:您应该使用全局修饰符

在这里测试: https//regex101.com/r/yilfcn/1请参阅这篇文章关于如何应用它: javascript regexp删除所有特殊字符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM