Get part of a string using jQuery

2020-05-21 08:56发布

问题:

HTML code:

<div id="block-id-45"></div>

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

回答1:

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



回答2:

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.



回答3:

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];
    .............
    .............
})