Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract number from a string in javascript

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.

like image 284
Saurabh Kumar Avatar asked Aug 11 '11 21:08

Saurabh Kumar


People also ask

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

How do you cut a number in JavaScript?

In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.


1 Answers

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); 
like image 112
Alex Wayne Avatar answered Oct 18 '22 18:10

Alex Wayne