Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

jquery - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...