如何使用javascript替换除数字[0-9]以外的所有字符? [英] How to replace all char except number [0-9] using javascript?

查看:123
本文介绍了如何使用javascript替换除数字[0-9]以外的所有字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to replace all char except number [0-9] using Javascript?

这是我的代码,

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...时,我的代码无法替换点[.] 我也该如何替换点[.]?

But when user fill 012345... my code can not replace dot [.] How can I do for replace dot [.] too ?

推荐答案

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

If you only want to keep numbers, then replace everything that isn't a number \d = number.

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

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

The possible regular expressions to use are:

/\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表示要匹配所有可能的搜索,因此不需要使用+来匹配其他任何内容.

The g means to match all possibilities of the search, so there is no need to use + to match anything else.

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

You'll find this tool very useful when working with regular expressions and it has an explanation of the possible characters to use at the bottom right.

这篇关于如何使用javascript替换除数字[0-9]以外的所有字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆