jQuery / Get numbers from a string

前端 未结 8 2173
北海茫月
北海茫月 2020-12-14 14:11

I have a button on my page with a class of comment_like and an ID like comment_like_123456 but the numbers at the end are variable; could be 1 to 1

相关标签:
8条回答
  • 2020-12-14 14:27

    You can try this. it will extract all number from any type of string.

    var suffix = 'comment_like_6846511';
    alert(suffix.replace(/[^0-9]/g,''));
    

    DEMO

    0 讨论(0)
  • 2020-12-14 14:27

    http://jsfiddle.net/hj2nJ/

    var x = 'comment_like_6846511';
    var y = '';
    
    for (i = 0; i < x.length; i++)
    {
        if ("" + parseInt(x[i]) != "NaN") //if the character is a number
            y = y + x[i];
    }
    
    document.write(y);
    
    0 讨论(0)
  • 2020-12-14 14:28

    You can get it like this:

    var suffix = 'comment_like_123456'.match(/\d+/); // 123456
    

    With respect to button:

    $('.comment_like').click(function(){
      var suffix = this.id.match(/\d+/); // 123456
    });
    
    0 讨论(0)
  • 2020-12-14 14:33

    jQuery is not a magic bullet. Use Javascript!

    var temp = "comment_like_123456".split("_")
    alert(temp[2])
    
    0 讨论(0)
  • 2020-12-14 14:35

    Just get the id and run it through a regex.

    $(mybutton).click(function() {
        var num = parseInt(/^.*\_(\d+)$/.exec(this.id)[1])
    });
    
    0 讨论(0)
  • 2020-12-14 14:38

    This would be the easiest way to grab number from a string using jquery.

    $(function(){
    	 $('.comment_like').click(function() {
        var element_id = $(this).attr('id');
        var number = element_id.match(/\d+/);
        
        alert(number);
    
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class='comment_like' id='comment_like_123456'>Click Me To Get a number from string</button>

    0 讨论(0)
提交回复
热议问题