Jonathan
Jonathan

Reputation: 1669

How to get the last name from the string

I have the following string.

var str = "\\Desk-7\e\cars\car1.jpg";

I want to get car1.jpg. How can i get that using jquery or javascript

Upvotes: 1

Views: 119

Answers (6)

first split then get it

var abc[] = str.split("\\")
var name = abc[abc.length-1];

Upvotes: 1

user235273
user235273

Reputation:

"\\Desk-7\e\cars\car1.jpg".match(/\b[^/]+$/);    //["Desk-7ecarscar1.jpg"]

Upvotes: 1

John Kiernander
John Kiernander

Reputation: 4904

Or could be done with:

var str = "\\\\Desk-7\\e\\cars\\car1.jpg";
var name = str.slice(str.lastIndexOf("\\") + 1);

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

NOTE: str should be: var str = "\\\\Desk-7\\e\\cars\\car1.jpg"; if hardcoded in code

var car1 = str.split('\\').pop();

Upvotes: 6

maximus ツ
maximus ツ

Reputation: 8065

Can be done by

function basename(path) {
 return path.replace(/\\/g,'/').replace( /.*\//, '' );
}

Upvotes: 2

Anand
Anand

Reputation: 14915

use str .split('\\') and then the last index

Upvotes: 1

Related Questions