如何使用JavaScript替换数字[0-9]以外的所有字符?

sut*_*kon 1 javascript jquery replace

如何0-9使用Java脚本替换数字[ ] 以外的所有字符?

这是我的代码

function test_fn(xxx) {
  var xxx = xxx.replace(/[^0-9,.]+/g, "");
  document.getElementById("fid").value = xxx;
}
Run Code Online (Sandbox Code Playgroud)
<input onkeyUp="test_fn(this.value)" id="fid">
Run Code Online (Sandbox Code Playgroud)

但是,当用户填写012345...我的代码时,不能替换点[ .]怎么也可以替换点[ .]?

OwC*_*lie 6

如果只想保留数字,则替换所有非数字\ d =数字。

function test_fn(xxx) {
  var xxx = xxx.replace(/[^\d]/g, "");
  document.getElementById("fid").value = xxx;
}
Run Code Online (Sandbox Code Playgroud)

可能使用的正则表达式为:

/\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
Run Code Online (Sandbox Code Playgroud)

g表示匹配所有可能的搜索,因此无需使用+来匹配其他任何内容。

在使用正则表达式时,您会发现此工具非常有用,并且在右下角说明了可能使用的字符。