javascript 删除除破折号以外的非数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26202837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:39:07  来源:igfitidea点击:

Remove non numeric characters except dash

javascript

提问by user3142695

I need to remove all non numeric characters except the dash. This is my attempt (based on: Regex to get all alpha numeric fields except for comma, dash and single quote):

我需要删除除破折号以外的所有非数字字符。这是我的尝试(基于:正则表达式获取除逗号、破折号和单引号之外的所有字母数字字段):

var stripped = mystring.replace(/[-0-9]+/g, '');

But that doesn't work :-(

但这不起作用:-(

回答by David says reinstate Monica

I'd suggest:

我建议:

var stripped = string.replace(/[^0-9\-]/g,'');

JS Fiddle demo.

JS小提琴演示

^in the character class (within the [and ]) is the NOT operator, so it matches characters which are not0-9or the (escaped) -character.

^在字符类中(在[and 内])是 NOT 运算符,因此它匹配不是0-9或(转义)-字符的字符。

As noted in the comment to this answer, by Ted Hopp, it's not necessary to escape the -when it's the last character, but I habitually do so in order to save having to remember that proviso.

正如Ted Hopp在对这个答案的评论中所指出的,-当它是最后一个字符时没有必要转义,但我习惯性地这样做是为了省去记住那个附带条件。

References:

参考: