Extract a number from a string (JavaScript)

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

    You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:

        var color = $( this ).css( "background-color" );
        var r = parseInt(color.match(/\d+/g)[0]);
        var g = parseInt(color.match(/\d+/g)[1]);
        var b = parseInt(color.match(/\d+/g)[2]);
    

提交回复
热议问题