繁体   English   中英

删除字符串中不是字母或数字的所有字符

[英]Remove all characters that are not letters or numbers in a String

我怎样才能删除所有不是字母或'数字'的字符?

我有一个字符串:

var string = 'This - is my 4 String, and i - want remove all characters 49494 that are not letters or "numbers"';

我想转变成这个:

var string = 'This is my 4 String and i want remove all characters 49494 that are not letters or numbers'

这个有可能?

谢谢!!

你可以使用这样的正则表达式:

[\W_]+

我们的想法是匹配\\W一个非单词字符(那些不是AZaz0-9_字符)并且还明确地添加_ (因为下划线被认为是单词字符)

工作演示

var str = 's - is my 4 String, and i - want remove all characters 49494 that are not letters or "numbers"';     
var result = str.replace(/[\W_]+/g, ' ');

我喜欢这样做的方法是使用RegEx。 这将选择所有计数器和计数器,并将其替换为空或删除它们:

string = string.replace(/[^\s\dA-Z]/gi, '').replace(/ +/g, ' ');

Explanantion:

[^  NOT any of there
  \s  space
  \d  digit
  A-Z letter
]

是的,可以使用正则表达式

string = string.replace(/[^a-z0-9]+|\s+/gmi, " ");

暂无
暂无

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

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