如何使用 Javascript 替换除数字 [0-9
] 之外的所有字符?
这是我的代码,
function test_fn(xxx) {
var xxx = xxx.replace(/[^0-9,.]+/g, "");
document.getElementById("fid").value = xxx;
}
<input onkeyUp="test_fn(this.value)" id="fid">
但是当用户填写 012345...
我的代码无法替换点 [.
]
我该如何替换点 [.
] 呢?
最佳答案
如果您只想保留数字,则替换所有不是数字的内容\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
/[^0-9,\.]/g //. is a wildcard character, escape it to target a .
g 表示匹配搜索的所有可能性,因此无需使用 + 来匹配任何其他内容。
你会发现 this tool在使用正则表达式时非常有用,它在右下角解释了可能使用的字符。
关于javascript - 如何使用 javascript 替换除数字 [0-9] 之外的所有字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45730059/