views:

100

answers:

4

I am using the code below to send an ID to my page:

The image names will always look like this 12.jpg 12-1.jpg 12-2.jpg 12-3.jpg e.t.c

I need to alter the line below so it will only send the 12 not the -1,-2,-3 e.t.c My code below already removes the .jpg part

var id = $(this).attr('src').split('/').pop().replace('.jpg','');
A: 

Remove trailing hyphen separated parts:

id= id.split('-')[0]
bobince
Hopefully there's no other dashes allowed in the filename :)
thenduks
I added your example like so var id = $(this).attr('src').split('/').pop().replace('.jpg',''); id = id.split('-')[0];was that right?
Andy
A: 
var id = $(this).attr('src').split('/').pop().replace('.jpg','');
var hyphenIndex = id.indexOf('-');
id = hyphenIndex > 0 ? id.substring(0, hyphenIndex) : id;
Dustin Fineout
Unfortunately this didnt work. Thanks for your efforts
Andy
A: 

How about a regex instead?

var id = $(this).attr('src').replace( /(-\d+)?\.jpg/, '' );
thenduks
unfortunately this didnt work
Andy
Can you be more specific? It works for me. I should have put a `\` before the `.` in `.jpg`, maybe that will help.
thenduks
Err, that's a '\' before the . in .jpg. Also if your filename is .jpeg of course this wont work so you could do: jpe?g
thenduks
A: 

like bobince, this should work...

var id = $(this).attr('src').split('/').pop().split('-')[0].replace('.jpg','');
luckykind