Remove input letters using Javascript and regular expression [duplicate]

0

I have an input field that gets a value. I would like to remove letters and special characters from the value of this input, leaving only numbers remaining. I think it would be easier to use a replace with a regular expression, but I can not. Could someone help me?

I've tried it like this:

valor.replace(/\d|,/g, "");

It just does not do anything.

    
asked by anonymous 07.04.2016 / 20:09

3 answers

1

Hello,

My suggestion would be that you use masks in JQuery, which would make your life a lot easier. I believe that if you follow the link below you can succeed.

link

Any questions, just talk = D

Hugs,

    
07.04.2016 / 20:15
1

You can configure the tag to accept only numbers, as below:

<input type="number"/>

If you want something more "secure", you can still do a function that checks character by character as the user types. For example:

function allowOnlyNumbers(e) {
    var tecla = (window.event) ? event.keyCode : e.which;
    if ((tecla > 47 && tecla < 58)) return true;
    else {
        if (tecla == 8 || tecla == 0) return true;
        else return false;
    }
};
<input id="input" type="number" onkeypress="return allowOnlyNumbers(event)"/>

That way, even if the user deletes the input type, you will not be able to type letters or special characters yet.

    
07.04.2016 / 23:49
0

/*
Converte caracteres full width (zenkaku) para o half width (hankaku) 
O zenkaku são caracteres disponíveis nos conjuntos de caracteres japoneses.
Exemplo, 1234567890 são números, porém, a expressão regular [^0-9\.] não os reconhece como números. Caso queira prover suporte a esse tipo de entrada, utilize o conversor da função ZenkakuToHankaku().
*/
function ZenkakuToHankaku(str) {
return str.replace(/[A-Za-z0-9]/g,function(s){return String.fromCharCode(s.charCodeAt(0)-0xFEE0)});
}

/*
Remove tudo que não for número
*/
function NumberOnly(str) {
return ZenkakuToHankaku(str).replace(/[^0-9\.]+/g, '');
}

/*
string para teste
*/
str = '123abc123文字 éã456';

/*
mostra o resultado no console (pressione CTRL+SHIFT+I no chrome)
*/
console.log(str = NumberOnly(str));

/*
teste, exibe o resultado no corpo html
*/
document.write(str);
    
07.04.2016 / 20:41