Extract a number from a string (JavaScript)

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

    Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string

    function retnum(str) { 
        var num = str.replace(/[^0-9]/g, ''); 
        return parseInt(num,10); 
    }
    

    console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
    console.log('#box2'.replace(/[^0-9]/g, ''));

提交回复
热议问题