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.
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.
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);
parseInt is optional, you should use it to prevent accidental parsing of a number as octal. If the span contains "0700ms", that will not return 700 as a result but will be 448!parseInt('ms120'.replace(/[^0-9\.]/g, ''), 10);parseInt() won't work if the string doesn't begin with number like already noted in comments.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);
parseInt(), you don't need the regex matching. Kudos for providing the radix parameter, though.You could use the parseInt() function
var number = parseInt($("span").text())
radix parameter to parseInt().in general for numbers no mather negative or positive
<div>
blah blah
<span>285blahblah</span>
</div>
var html= document.getElementsByTagName('div')[0].innerHTML;// or $('div').html() if jquery
var number = parseFloat(html.match(/-*[0-9]+/));
This extracted number from string for me:
function extractNumberFromString(inputString){
const number=[];
for(const char of inputString){
if(!isNaN(char)){
number.push(parseInt(char));
}
}
return number;
}
const i="election2025india";
console.log(extractNumberFromString(i));
//OUTPUT :- [ 2, 0, 2, 5 ]