Get part of a string using jQuery

后端 未结 3 1723
孤独总比滥情好
孤独总比滥情好 2021-02-03 12:20

HTML code:

How can I get number \"45\" of string using jQuery?

相关标签:
3条回答
  • 2021-02-03 12:35

    To return the number at the end of an id attribute use

    $(this).attr("id").match(/[\d]+$/);
    

    The above will return 45 if $(this) is <div id="block-id-45"></div>

    jsFiddle example

    The way the above works is that you retrieve the id of the element using .attr(), then you look at the id and use .match() to recover the number at the end of it. /[\d]+$/ is a regex. [\d] means one digit + means one or more (of the digits). and $ means the end of the line.


    You can use this function to retrieve the numbers from the end of all divs with an id that starts with block-id- by making use of the attribute starts with selector [name^=value] and .each():

    Practical usage:

    $(function() {
    
          // Select all DIS that start with 'block-id-'
          //   and iterate over each of them.
        $("div[id^='block-id-']").each(function() {
    
              // You could push this data to an array instead.
              // This will display it.
            $("body").append( "Id number: " + 
                                // This is the number at the end
                              $(this).attr("id").match(/[\d]+$/) +
                              "<br/>" );
        });
    });​
    

    jsFiddle example

    0 讨论(0)
  • 2021-02-03 12:37

    You don't need (or particularly want) jQuery for this (it's very useful for lots of other things, just not particularly for this). Straight JavaScript and DOM:

    var div = document.getElementById('block-id-45');
    var n = div.id.lastIndexOf('-');
    var target = div.id.substring(n + 1);
    

    Live example: http://jsbin.com/osozu

    If you're already using jQuery, you can replace the first line with:

    var div = $('#block-id-45')[0];
    

    ...but there's little if any reason to.

    0 讨论(0)
  • 2021-02-03 12:45

    Using jQuery, simply:

    $("[id='block-id-45']").attr("id").split("-")[2]
    

    For all block-id-##, you can use mask pattern from Peter's answer:

    $("[id^='block-id-']").click(function(){
    
        row_id = $(this).attr("id").split("-")[2];
        .............
        .............
    })
    
    0 讨论(0)
提交回复
热议问题