如何使用javascript替换除数字[0-9]以外的所有字符?
如何使用Javascript替换除数字[如何使用javascript替换除数字[0-9]以外的所有字符?,javascript,jquery,replace,Javascript,Jquery,Replace,如何使用Javascript替换除数字[0-9]之外的所有字符 这是我的密码 功能测试(xxx){ 变量xxx=xxx。替换(/[^0-9,.]+/g,”); document.getElementById(“fid”).value=xxx; } 只需从正则表达式中去掉点和逗号即可 顺便说一句,您可以将元素(this)作为参数,并更新值属性。使用此模式,您还可以将该函数用于其他输入 功能测试\u fn(元件){ element.value=element.value.replace(/[^0
0-9
]之外的所有字符
这是我的密码
功能测试(xxx){
变量xxx=xxx。替换(/[^0-9,.]+/g,”);
document.getElementById(“fid”).value=xxx;
}
只需从正则表达式中去掉点和逗号即可
顺便说一句,您可以将元素(this
)作为参数,并更新值
属性。使用此模式,您还可以将该函数用于其他输入
功能测试\u fn(元件){
element.value=element.value.replace(/[^0-9]+/g,“”);
}
如果您只想保留数字,则替换所有不是数字的\d=number
function test_fn(xxx) {
var xxx = xxx.replace(/[^\d]/g, "");
document.getElementById("fid").value = xxx;
}
可能使用的正则表达式有:
/\D/g //\D is everything not \d
/[^\d]/g //\d is numerical characters 0-9
/[^0-9]/g //The ^ inside [] means not, so in this case, not numerical characters
g表示匹配搜索的所有可能性,因此不需要使用+来匹配任何其他内容
在使用正则表达式时,您会发现它非常有用,它在右下角有可能使用的字符说明。
<input type="text" value="" onkeypress="return isNumber(event)" />
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</script>
函数isNumber(evt){
evt=(evt)?evt:window.event;
var charCode=(evt.which)?evt.which:evt.keyCode;
如果(字符码>31&(字符码<48 | |字符码>57)){
返回false;
}
返回true;
}
将正则表达式更改为以下内容:
var xxx = "12.3te.st.45";
xxx = xxx.replace(/[^0-9]+/g, "");
alert(xxx);
通过这种方式,它将删除任何不是0-9的内容。如果您不习惯使用正则表达式,则不必使用正则表达式。 这是一个非正则表达式的版本,很容易理解
var str = "12AGB.63"
str = str.split("").filter(function(elem){
return parseInt(elem)
}).join("")
参数为“”的拆分函数将数组转换为字符串
参数为“”的join函数将字符串转换为数组
以下是Array.prototype.filter的说明:
是否也应替换“逗号”?您最多需要1个点
或者不需要任何人?@Nina Scholz-他不需要这个点。您可以使用\D
而不是[^\D]
使用代码片段而不是JSFIDLE,使用[]按钮即可。它更容易阅读和使用。我可以填写这121.99900为什么不替换点