Paste numbers without formatting

Asked

Viewed 31 times

1

How could I do to remove points from a number formats?

For example, I take and copy a value 000.000.000 and I’ll put it on mine input, it would automatically leave this formatting of it and would "000000000".

I found a mask, only she’s not running here.

My input:

<input type="text" class="form-control" name="var_est" value="" onchange="tiraMascara(this)" placeholder="" data-size="small" mask="#000.000.000.000" data-only-numbers="" required="required" style="width: 100%;">

The mask:

<script>
function removeMaskMoney (x){
    x = ""+x;
    y = 0;
    if ((x.replace(",", ".") != x )){
        if (x.replace(".", "") != x ){
            aux = x;
            x = x.replace(".", "");    
            x = x.replace(".", "");                            
        }
        else {
            aux = x;
        }
        if(x.replace(",", ".") != x){
            x = x.replace(",", ".")
        }else{
            x = aux;
        }
    }
    if (isNaN(parseFloat(x)) ){
        x = 0;
    }else{
        x = parseFloat(x)
    }
    return x;
}

function tiraMascara(e){
    value = removeMaskMoney ($(e).val());
    $("[name=var_est_sem_mask]").val( value)
}
</script>

1 answer

3

You can use regular expression and String.replace() to replace every character that is not a number by ''.

"000.000.000".replace(/\D+/g, '');  // "000000000"

The \D causes Regex to marry any character other than a number([0-9]).

The + is a quantifier that means "once or more". That is, he will marry with any character other than a number that repeats itself 1 or more times.

And finally, the flag g specifies that replace will be global, i.e., it will not stop at the first replacement.

A very simple example working:

var $input = $('#teste');
var $feedback = $('#feedback');

$('#btn').on('click', function() {
  $feedback.html($input.val().replace(/\D+/g, ''))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input id="teste"/>
<button id="btn">!!!</button>
<div id="feedback"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.