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

标签 javascript jquery replace

如何使用 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/

相关文章:

javascript - setInterval 道场示例

javascript - 监听某个页面的 jQuery 加载事件

Javascript - 用于删除特殊字符但还保留希腊字符的正则表达式

jquery - 如果主体类发生变化,使用 jQuery 替换 CSS 样式表

javascript - 如何从另一个js文件调用一个js文件中的函数

javascript - 如何按 codePoint 对 JavaScript 字符串进行排序?

javascript - Controller 中范围数据中的变量

javascript - 如何在固定柱形图(highcharts)中动态添加点放置和点填充

javascript - 更改现有 Kendo Grid 上的选项的正确语法是什么?

javascript - 如何在 JavaScript 中替换字符串中最后一次出现的两个字符之间的字符?