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

若如初见. 提交于 2020-01-24 21:54:08

问题


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

This is my code,

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

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


回答1:


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

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.




回答2:


Change your regex to the following:

var xxx = "12.3te.st.45";
xxx = xxx.replace(/[^0-9]+/g, "");
alert(xxx);

https://jsfiddle.net/891n0hx0/

This way it removes anything that is not 0-9.




回答3:


<input type="text" value="" onkeypress="return isNumber(event)" />

<script type="text/javascript">
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
</script>



回答4:


Just take the dot and comma out of the regular expression.

BTW, you could just take the element (this) as parameter and update the value property. With this pattern, you could use the function for other inputs as well.

function test_fn(element) {
    element.value = element.value.replace(/[^0-9]+/g, "");
}
<input onkeyUp="test_fn(this)" id="fid">



回答5:


You do not have to use regex if you're not comfortable with. Here is a non regex version easy to understand.

var str = "12AGB.63"
str = str.split("").filter(function(elem){
  return parseInt(elem)
}).join("")

split function with "" as parameter will transform Array to String.

join function with "" as parameter will transform String to Array

Here is a description of Array.prototype.filter :

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter



来源:https://stackoverflow.com/questions/45730059/how-to-replace-all-char-except-number-0-9-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!