Javascript 正则表达式替换除数字和小数点以外的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4572194/
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
Regex to replace everything except numbers and a decimal point
提问by guildsbounty
I have a text field that needs to remain only text or decimal. Here is the code that I'm currently using to replace everything except numbers and a decimal point. Issue is, I can't figure out a regex that will identify everything else
我有一个只需要保留文本或十进制的文本字段。这是我目前用来替换除数字和小数点以外的所有内容的代码。问题是,我想不出一个可以识别其他所有内容的正则表达式
document.getElementById(target).value = newVal.replace(/\D[^\.]/g, "");
The \D works fine, but I've tried (?!.), (?!\.), [^.], [^\.]
and so on...
\D 工作正常,但我已经尝试过(?!.), (?!\.), [^.], [^\.]
等等......
Any suggestions for a regular expression that identifies positively with anything except a number or a decimal?
对于正则表达式,除了数字或小数以外的任何东西都有什么建议吗?
Thanks for the help
谢谢您的帮助
回答by Chandu
Use this:
用这个:
document.getElementById(target).value = newVal.replace(/[^0-9.]/g, "");
回答by lubosdz
Removing only decimal part can be done as follows:
可以按如下方式仅删除小数部分:
number.replace(/(\.\d+)+/,'');
This would convert 13.6667px into 13px (leaving units px untouched).
这会将 13.6667px 转换为 13px(保持单位 px 不变)。
回答by Beachhouse
Try this:
尝试这个:
document.getElementById(target).value = newVal.replace(/^\d+(\.\d{0,2})?$/, "");
document.getElementById(target).value = newVal.replace(/^\d+(\.\d{0,2})?$/, "");
回答by divya
Check the link Regular Expression Demo
检查链接正则表达式演示
use the below reg exp
使用下面的正则表达式
[a-z] + [^0-9\s.]+|.(?!\d)
[az] + [^0-9\s.]+|.(?!\d)