Extract a number from a string (JavaScript)

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

    You can use Underscore String Library as following

    var common="#box"
    var href="#box1"
    
    _(href).strRight(common)
    

    result will be : 1

    See :https://github.com/epeli/underscore.string

    DEMO:
    http://jsfiddle.net/abdennour/Vyqtt/
    HTML Code :

    img1 img2 img3 img4

    JS Code :

    var comm="#box"
    $('a').click(function(){
      $('div').html(_($(this).attr('href')).strRight(comm))})
    

    if you have suffix as following :

    href="box1az" 
    

    You can use the next demo :

    http://jsfiddle.net/abdennour/Vyqtt/1/

    function retrieveNumber(all,prefix,suffix){
     var left=_(all).strRight(prefix);
     return _(left).strLeft(suffix);
    
    }
    

提交回复
热议问题