Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get part of a string using jQuery

HTML code:

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

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

like image 952
VladY Avatar asked Sep 15 '10 22:09

VladY


2 Answers

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

like image 117
Peter Ajtai Avatar answered Nov 16 '22 03:11

Peter Ajtai


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.

like image 26
T.J. Crowder Avatar answered Nov 16 '22 02:11

T.J. Crowder