Get only numbers in an input that receives XX ml (example: 200ml)

5

I'm using Jquery's mask to automatically place the ml (milliliter) suffix in the input that gets the size of a bottle.

being the id of the input #tape:

var tamanho = $("#tamanho").val();

A 200 ml example will only pick up the 200 value.

but console.log(tamanho) returns 200 ml and I only need the value if it is not impossible to do calculations.

Which regular expression should I use to capture only input numbers? where should I put this regular expression to add the value to variable tamanho ?

    
asked by anonymous 30.12.2016 / 21:27

1 answer

4

If this string has values first and letters / units then you can use parseInt that ignores what comes after the numbers and returns a number, ie : number .

var tamanho = parseInt($("#tamanho").val(), 10);

If you need values with a decimal part, there you get a little more specific and you can do it like this:

var string = $("#tamanho").val().replace(/\./g, '').replace(',', '.');
var tamanho = parseFloat(string.match(/[\d\,\.]+/)[0]);

parseFloat transforms a string into part number decimal, but is more limited than parseInt , you must have the string only with digits and using the dot to indicate the decimal part, not the comma.

Examples:

var tamanhoSimples = '200 ml';
console.log(parseInt(tamanhoSimples, 10));

var tamanhoComParteDecimal = '5.200.544,46 ml';
var stringLimpa = tamanhoComParteDecimal.replace(/\./g, '').replace(',', '.');
console.log(parseFloat(stringLimpa.match(/[\d\,\.]+/)[0]));
    
30.12.2016 / 21:41