-2

I have this line of code for jQuery to get the src of an image $(this).find("img").attr("src") so, I'm sure as you all know it will return something like http://www.mysite.com/this.image.png

Is there any such statement that can allow me to grab the url without the file extension so: http://www.mysite.com/this.image so I can add some things to the url like pview for an image preview file or big for a large image etc.

Any help would be appreciated. Thanks!

Adjit
  • 10,134
  • 12
  • 53
  • 98

3 Answers3

2

try this:

 var img = $(this).find("img").attr("src");  
 img = img.substring(0,img.lastIndexOf("."));
T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • what is error.... lemme check the method, i assume img is a string that has a value? – T McKeown Dec 26 '13 at 21:39
  • error says `Uncaught TypeError: Cannot call method 'lastIndexOf' of undefined`. Ooooh, actually I made a mistake, I was calling `$(this)` outside of my method so it doesn't know what `this` is. – Adjit Dec 26 '13 at 21:41
  • yeah, sounds like the var img didn't contain a string value. – T McKeown Dec 26 '13 at 21:42
1

You can use:

var url   = $(this).find("img").attr("src");
var parts = url.match(/(.*)\.([^\\/]+)$/);
console.log(parts[0]); # => http://www.mysite.com/this.image
console.log(parts[1]); # => png
console.log(parts[0] + '.big.' + parts[1]);
#=> http://www.mysite.com/this.image.big.png

Regex Explanation:

(.*)        // capture all the characters before
\.          // .. a dot character
([^\\/]+)$  // capture any characters afterwards (that are not `\` or `/`)
Stoic
  • 10,536
  • 6
  • 41
  • 60
  • can you elaborate on your regexp please? – Adjit Dec 26 '13 at 21:20
  • good answer, and I really like the idea of having an array with the substrings, but for some reason I just don't understand regexp, and I will be using the same file extensions so I went with the substring method instead. – Adjit Dec 26 '13 at 21:45
1

Check out this tutorial for the JavaScript substring() function. It allows you to extract characters from a string. It should look something like this (not tested):

var url = $(this).find("img").attr("src");
var urlLength = url.length -4; //The -4 is for the last 4 chars. Example ".png"
url = url.substring(0, urlLength);

I hope this helps!

Moduo
  • 623
  • 6
  • 17