Reputation: 997
I have an id:
div id ="untitled-region-5"
I want to grab that id and remove 4 from it and then do some code with the new id.
So far I am trying something like this from reading about how to perform this:
var n = $(this).attr('id').match(/untitled-region-(\d+)/)[1];
But I don't know how to remove 4 from the integer.
Upvotes: 2
Views: 93
Reputation: 5008
var id = $("div").attr("id");
var n = parseInt(id.substring(id.lastIndexOf("-") + 1), 10);
I made a jsFiddle too: http://jsfiddle.net/YEWQQ/
Upvotes: 1
Reputation: 5781
<div id ="untitled-region-5">
just take n and subtract 4
var n = $('div').attr('id').match(/untitled-region-(\d+)/)[1];
var newNumber = n-4;
$('div').attr('id','untitled-region-'+newNumber);
Upvotes: 1
Reputation: 700422
It's still a string, that's why you can't easily use it in math. Some operations work, because they will implicitly convert the value to a number.
Use parseInt
to explicitly do the conversion, so that you know what you have:
var n = parseInt($(this).attr('id').match(/\d+$/)[0]);
n -= 4;
Upvotes: 4