Extract a number from a string (JavaScript)

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

    I think this regular expression will serve your purpose:

    var num = txt.replace(/[^0-9]/g,'');
    

    Where txt is your string.

    It basically rips off anything that is not a digit.

    I think you can achieve the same thing by using this as well :

    var num = txt.replace(/\D/g,'');
    

提交回复
热议问题