Javascript: Replace characters after _

javascript, replace

Solution

You can it like this:

var testURL = "dvuivnhuiv_ew";
var output = testURL.substring(0, testURL.lastIndexOf('_') + 1);
console.log(output);

Problem

I'm trying to do something which seems fairly basic, but can't seem to get it working. I'm trying to strip the characters after the last instance of an underscore. I have this string, for example: www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg and I'm trying to strip out the 'tn.jpg' to produce: www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_ I tried doing .slice(0,-6) but that will only work for instances of _tn.jpg and not _med.jpg. Ultimately, I'm going to be swapping in different sizes of images (_med.jpg, _full.jpg etc.) and it needs to be only after the last underscore (there might be underscores in the URL). Any help would be greatly appreciated! Zack

Original source