Javascript: replace characters after _

I'm trying to do something that seems pretty simple, but doesn't seem to be able to make it work.

I am trying to remove characters after the last instance of the underscore.

I have this line, for example:

WWW / image / 10/20120412 / 28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg

and I'm trying to cut out "tn.jpg" to create:

WWW / image / 10/20120412 / 28-696-b0b9815463e47c9371b02b7202788a75_

I tried doing .slice (0, -6), but this will only work for _tn.jpg instances, not _med.jpg.

Ultimately, I’m going to exchange images of different sizes (_med.jpg, _full.jpg, etc.), and this should only be after the last underscore (there may be underscores in the URL).

Any help would be greatly appreciated!

Zack

+5
3

:

var testURL = "dvuivnhuiv_ew";
var output = testURL.substring(0, testURL.lastIndexOf('_') + 1);
console.log(output);
+11
var path = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var index = path.lastIndexOf('_');
path = path.substring(0, index+1);
alert(path);
+4
var url = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var result = url.substring(0, url.lastIndexOf('_')+1);
alert(result);

+2

All Articles