Extract a number from a string (JavaScript)

前端 未结 22 1377
灰色年华
灰色年华 2020-11-22 06:38

I have a string in JavaScript like #box2 and I just want the 2 from it.

I tried:

var thestring = $(this).attr(\'href\');
var          


        
相关标签:
22条回答
  • 2020-11-22 06:55

    You can do a function like this

    function justNumbers(string) 
        {
            var numsStr = string.replace(/[^0-9]/g,'');
            return parseInt(numsStr);
        }
    

    remember: if the number has a zero in front of it, the int wont have it

    0 讨论(0)
  • 2020-11-22 06:55

    If someone need to preserve dots in extracted numbers:

    var some = '65,87 EUR';
    var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
    console.log(number); // returns 65.87
    
    0 讨论(0)
  • 2020-11-22 06:56

    You can use Underscore String Library as following

    var common="#box"
    var href="#box1"
    
    _(href).strRight(common)
    

    result will be : 1

    See :https://github.com/epeli/underscore.string

    DEMO:
    http://jsfiddle.net/abdennour/Vyqtt/
    HTML Code :

    <p>
        <a href="#box1" >img1</a>
        <a href="#box2" >img2</a>
        <a href="#box3" >img3</a>
        <a href="#box4" >img4</a>
    </p>
    <div style="font-size:30px"></div>
    

    JS Code :

    var comm="#box"
    $('a').click(function(){
      $('div').html(_($(this).attr('href')).strRight(comm))})
    

    if you have suffix as following :

    href="box1az" 
    

    You can use the next demo :

    http://jsfiddle.net/abdennour/Vyqtt/1/

    function retrieveNumber(all,prefix,suffix){
     var left=_(all).strRight(prefix);
     return _(left).strLeft(suffix);
    
    }
    
    0 讨论(0)
  • 2020-11-22 06:56
    var elValue     = "-12,erer3  4,-990.234sdsd";
    
    var isNegetive = false;
    if(elValue.indexOf("-")==0) isNegetive=true;
    
    elValue     = elValue.replace( /[^\d\.]*/g, '');
    elValue     = isNaN(Number(elValue)) ? 0 : Number(elValue);
    
    if(isNegetive) elValue = 0 - elValue;
    
    alert(elValue); //-1234990.234
    
    0 讨论(0)
  • 2020-11-22 06:57

    You can use regular expression.

    var txt="some text 2";
    var numb = txt.match(/\d/g);
    alert (numb);
    

    That will alert 2.

    0 讨论(0)
  • 2020-11-22 06:57

    You can extract numbers from a string using a regex expression:

    let string = "xxfdx25y93.34xxd73";
    let res = string.replace(/\D/g, "");
    console.log(res); 
    

    output: 25933473

    0 讨论(0)
提交回复
热议问题