Extract a number from a string (JavaScript)

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

    Here's a solt. that checks for no data

    var someStr = 'abc'; // add 123 to string to see inverse
    
    var thenum = someStr.match(/\d+/);
    
    if (thenum != null )
    {
        console.log(thenum[0]);
    }
    else
    {
     console.log('no number');
    }
    

提交回复
热议问题