How to extract number from a string in javascript

前端 未结 9 677
清歌不尽
清歌不尽 2020-12-08 19:23

I have an element in javascript like follows:

 280ms

I want to extract 280 from the span element. How can I do it?

相关标签:
9条回答
  • 2020-12-08 20:13

    Will it always end in "ms"? You can do:

    var num = s.substring(0, s.length-2) 
    

    where s is the string in the span. To get this value, you can use text(), html(), or innerHTML on the span.

    0 讨论(0)
  • 2020-12-08 20:13

    using jquery is pretty simple. probably better giving the span an id though

    var mytext=replace($('span').text(),"ms","");
    

    edited to remove ms

    0 讨论(0)
  • 2020-12-08 20:23

    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);
    
    0 讨论(0)
提交回复
热议问题