How to extract number from a string in javascript
parseInt()
is pretty sweet.
HTML
<span id="foo">280ms</span>
JS
var text = $('#foo').text();
var number = parseInt(text, 10);
alert(number);
parseInt()
will process any string as a number and stop when it reaches a non-numeric character. In this case the m
in 280ms
. After have found the digits 2
, 8
, and 0
, evaluates those digits as base 10 (that second argument) and returns the number value 280
. Note this is an actual number and not a string.
Edit:
@Alex Wayne's comment.
Just filter out the non numeric characters first.
parseInt('ms120'.replace(/[^0-9\.]/g, ''), 10);
Try this:
var num = document.getElementById('spanID').innerText.match(/\d+/)[0];
jQuery version:
var num = $('span').text().match(/\d+/)[0]; // or $('#spanID') to get to the span
If you want as numeric value (and not as string), use parseInt:
var num = parseInt($('span').text().match(/\d+/)[0], 10);
Try the following
var strValue = // get 280m from the span
var intValue = parseInt(strValue.match(/[0-9]+/)[0], 10);