1

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

4
  • Is that your actual string... or did you mean to escape the backslashes? Commented Sep 12, 2013 at 10:47
  • 2
    Do you define the string like that or do you get a string like that? If you define it like that the result would be "\Desk-7ecarscar1.jpg" Commented Sep 12, 2013 at 10:48
  • @Anton you are correct if str is defined like that. Some escaping characters are missing Commented Sep 12, 2013 at 10:48
  • The string is coming from the controller. I am returning the filename form controller. There is no issue with chrome or safari or ff. The file is returning like this in ie only Commented Sep 12, 2013 at 10:52

6 Answers 6

6

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

var car1 = str.split('\\').pop(); 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for cuteness, but, out of interest, is there a cheaper way of doing this? In C++ (and Java) we can get the position of a final occurrence of a character and substring from that. Saves creating an container object.
@Bathsheba lastIndexOf() used with substring() but less readable
2

Can be done by

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

Comments

2

Or could be done with:

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

Comments

1

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

Comments

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

Comments

1

first split then get it

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.