Extract a number from a string (JavaScript)

前端 未结 22 1805
灰色年华
灰色年华 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: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
    

提交回复
热议问题