HTML code:
How can I get number \"45\" of string using jQuery?
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():
$(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]+$/) +
"
" );
});
});