Get part of a string using jQuery

后端 未结 3 1722
孤独总比滥情好
孤独总比滥情好 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

    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]+$/) +
                              "
    " ); }); });​

    jsFiddle example

提交回复
热议问题