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

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 ?



Solution 1:[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
/[^0-9,\.]/g   //. is a wildcard character, escape it to target a .

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.

Solution 2:[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.

Solution 3:[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>

Solution 4:[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">

Solution 5:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Airwavezx
Solution 3 Chandrika Shah
Solution 4
Solution 5 Nolyurn