Remove input letters using Javascript and regular expression

Asked

Viewed 5,600 times

0

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

I tried so:

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

Only it does nothing.

3 answers

1

1

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

<input type="number"/>

If you want something more "secure", you can still do a function that checks character by character, while the user type. 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)"/>

This way, even if the user deletes the input type, he still won’t be able to type letters or special characters.

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);

Browser other questions tagged

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