Javascript 正则表达式删除字母,除数字以外的符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6649327/
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-08-23 22:37:17  来源:igfitidea点击:

Regex to remove letters, symbols except numbers

javascriptregexsymbols

提问by MacMac

How can you remove letters, symbols such as ∞§??aoo?≥≤÷but leaving plain numbers 0-9, I want to be able to not allow letters or certain symbols in an input field but to leave numbers only.

你怎么能删除字母、符号,比如∞§??aoo?≥≤÷但留下纯数字 0-9,我希望能够在输入字段中不允许字母或某些符号,而只留下数字。

Demo.

演示

If you put any symbols like ? # ¢ ∞ § ? ? aor else, it still does not remove it from the input field. How do you remove symbols too? The \wmodifier does not work either.

如果您放置任何符号,例如? # ¢ ∞ § ? ? a或 else,它仍然不会将其从输入字段中删除。你如何删除符号?该\w修改也不起作用。

回答by alex

You can use \Dwhich means non digits.

您可以使用\Dwhich 表示非数字

var removedText = self.val().replace(/\D+/g, '');

jsFiddle.

js小提琴

You could also use the HTML5 numberinput.

您还可以使用HTML5数字输入

<input type="number" name="digit" />

jsFiddle.

js小提琴

回答by Klemen Tu?ar

Use /[^0-9.,]+/if you want floats.

/[^0-9.,]+/如果你想要浮动,请使用。

回答by bezmax

Simple:

简单的:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

^ - 表示不是

回答by Darin Dimitrov

Try the following regex:

尝试以下正则表达式:

var removedText = self.val().replace(/[^0-9]/, '');

This will match every character that is not(^) in the interval 0-9.

这将匹配间隔 0-9 中不是( ^) 的每个字符。

Demo.

演示

回答by Aziz Shaikh

If you want to keep only numbers then use /[^0-9]+/instead of /[^a-zA-Z]+/

如果您只想保留数字,请使用/[^0-9]+/代替/[^a-zA-Z]+/