如何使用 javascript 替换除数字 \[0-9\] 之外的所有字符?

新手上路,请多包涵

如何使用 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... 我的代码不能替换点 [ . ] 我该如何替换点 [ . ]–

原文由 suttakan mongkon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 327
1 个回答

如果您只想保留数字,则替换不是数字的所有内容 \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 表示匹配搜索的所有可能性,因此无需使用 + 来匹配任何其他内容。

您会发现 此工具 在处理正则表达式时非常有用,它在右下角对可能使用的字符进行了解释。

原文由 OwChallie 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题