Alex Rivera | Logout

How to extract number from a string in javascript

Asked 2011-08-11T21:51:05.070
39

I have an element in javascript like follows:

 <span>280ms</span>

I want to extract 280 from the span element. How can I do it? The content within the span element will be any number followed by ms.

Edit
Report

1 Answer

19

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);
answered 2011-08-11T21:53:19.803

Your Answer