How to extract number from a string in javascript

前端 未结 9 676
清歌不尽
清歌不尽 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 19:59

    You could use the parseInt() function

    var number = parseInt($("span").text())
    
    0 讨论(0)
  • 2020-12-08 20:01

    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]+/));
    

    http://jsfiddle.net/R55mx/

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

    Try the following

    var strValue = // get 280m from the span
    var intValue = parseInt(strValue.match(/[0-9]+/)[0], 10);
    
    0 讨论(0)
  • 2020-12-08 20:03

    Change the span in:

    <span id='msSpan'>280ms</span>
    

    Then you can do:

    alert($('#msSpan').text());
    
    0 讨论(0)
  • 2020-12-08 20:09

    var myNumber= $('span').text().replace(/[^d.,]+/,'');

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

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