I am trying to replace the id of a jQuery element for the next one as follows:
‘foo-1’ –> ‘foo-2’
And I finally ended with this:
$(this).attr('id',$(this).attr('id').replace(/-[0-9]*/,'-'+(parseInt($(this).attr('id').substring($(this).attr('id').indexOf('-')+1,$(this).attr('id').length))+1)));
Ugly, right?
Any Ideas of how I would improve this…..?
Use the replace callback function to simplify your code:
$2matches the first parentheses (which is ‘-‘ in your case),$3matches the digitals. You then prase the digital withparseInt()and increment it by one. Finally, you put together the replaced string with+string operator.