TraderZed
TraderZed

Reputation: 215

Javascript: Replace characters after _

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

Upvotes: 11

Views: 26387

Answers (4)

abde raouf
abde raouf

Reputation: 9

var url = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var result = url.substring( 0,url.indexOf('_')+1);
alert(result);
//or you can type only after _
var url = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var result = url.substring( url.indexOf('_'));
alert(result);
// (substring) is mean how much you want display chracter and where like from 0 to 63


// (indexOf) is mean number chracter on line


// note: if u have two _ i think will get some problme 

Upvotes: 0

user1150525
user1150525

Reputation:

You can it like this:

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

Upvotes: 21

The Alpha
The Alpha

Reputation: 146191

var url = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var result = url.substring(0, url.lastIndexOf('_')+1);
alert(result);

​Example

Upvotes: 3

Patrick Lee Scott
Patrick Lee Scott

Reputation: 8699

var path = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var index = path.lastIndexOf('_');
path = path.substring(0, index+1);
alert(path);

Upvotes: 5

Related Questions