javascript 用javascript替换非数字字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6097305/
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
replace nonNumeric characters with javascript?
提问by PsyGnosis
I use this regular expression phone validation
我使用这个正则表达式电话验证
but when anybody enters any special characters *-/()-_
in the input.. (except +
) I want to replace this characters with ""(none).
How can I do that?
但是当有人*-/()-_
在输入中输入任何特殊字符时..(除了+
)我想用“”(无)替换这些字符。我怎样才能做到这一点?
var phone = /^\+(90)[2-5]{1}[0-9]{9}$/;
回答by DavidJCobb
This will remove all non-numeric characters in a given string:
这将删除给定字符串中的所有非数字字符:
myString = myString.replace(/\D/g,"");
\D
matches anything that isn't a number; \d
matches a number.
\D
匹配任何不是数字的东西;\d
匹配一个数字。
Misread the question. To remove all non-numeric characters except +
, do:
误读了这个问题。要删除除 之外的所有非数字字符+
,请执行以下操作:
myString = myString.replace(/[^\d\+]/g,"");
回答by bjornd
var input = document.getElementById('phone');
input.onkeypress = function(){
input.value = input.value.replace(/[^0-9+]/g, '');
}