18

Say I have the following:

<img src="http://www.site.com/folder/pic.jpg">

This path could be anything, we basically want to get the "pic.jpg as a variable.

Currently we are doing it like so:

var first_img = $("#thumbnail-area li:first").find("img").attr("title");

Which sets the first_img variable as the image src, but we want to do a preg match kinda thing like in PHP to grab the "pic.jpg".

This has to work properly, so the path could be: folder/foo/bar/x982j/second822.jpg and it'd return second822.jpg

How can I do this?

alex
  • 479,566
  • 201
  • 878
  • 984
Latox
  • 4,655
  • 15
  • 48
  • 74

3 Answers3

23

You could use replace() which is like PHP's preg_replace() (it too accepts a PCRE, with some limitations such as no look behinds)...

str.replace(/.*\//, '')

jsFiddle.

Alternatively, you could use...

str.split('/').pop();

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
7

jQuery is not necessary here; Javascript supports regular expressions on its own, so jQuery is not part of the answer.

Javascript's regex replace function is simply called .replace(), and is a method on the string class. You would use it as follows:

var mystring = 'this is a string';
mystring.replace(/is a/,'might be a');
//mystring is now equal to 'this might be a string'.

That should be enough to get you started. Since you referenced preg_replace() in the question, I assume you already know how to use regular expressions well enough not to need a detailed discussion of how to solve your specific example.

Spudley
  • 166,037
  • 39
  • 233
  • 307
1

Working example here: http://jsfiddle.net/jkeyes/sxx3T/

var re = new RegExp(".*\/(.*)$");
var src="folder/foo/bar/x982j/second822.jpg";
var m = re.exec(src);
alert(m[1]); // first group 
John Keyes
  • 5,479
  • 1
  • 29
  • 48
  • the link to jsfiddle to show it working is good, but you should really post the code here in the answer as well, especially when it's as short as this one. – Spudley Oct 06 '11 at 11:48