0

This is my Temp url and I'm trying to get image name

var str='C:\fakepath\alfa_company.png';

my expected out put like this:

var url='alfa_company.png';
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Paras Raiyani
  • 748
  • 5
  • 10
  • Updated title as this is not jquery - jquery is for DOM manipulation, string manipulation is vanilla javascript. – freedomn-m May 30 '20 at 10:18

2 Answers2

3

In Javascript "\" has a special meaning. So, it doesn't get included in your resultant string.

Try

let u = String.raw`C:\fakepath\alfa_company.png`;
u.split("\\")[u.split("\\").length-1]

or

let u = String.raw`C:\fakepath\alfa_company.png`;
u.split("\\").pop()

to understand it better go through How can I use backslashes (\) in a string?

kokila
  • 294
  • 2
  • 8
  • Your answe is perfect working but me filepath store in variable and this situation String.raw function not working so any other function help me – Paras Raiyani May 30 '20 at 10:26
  • @MarcinWanago glad to help! IMO, there is no way you can manipulate the string to remove the "/" which is an escape character and not a backslash in javascript string. As soon as javascript gets it, "/" behaves like an escape char and not a backslash. You should receive the escaped string in the file value itself i.e. C:\\fakepath\\alfa_company.png – kokila May 30 '20 at 12:15
0

You don't need any jQuery for that :)

const path = 'C:\\fakepath\\alfa_company.png';
const filename = path.split('\\').pop(); // alfa_company.png

You need to use double backlashes because JavaScript treats them as escape characters.

Marcin Wanago
  • 624
  • 7
  • 11
  • thank you but only 1 back slash i am get in the file value – Paras Raiyani May 30 '20 at 10:08
  • @freedomn-m what was the reason for editing my answer? – Marcin Wanago May 30 '20 at 10:11
  • The `\\` in the first string is to generate the string that you already have as a string – freedomn-m May 30 '20 at 10:11
  • I converted it to a snippet so that OP can see it working. I also removed the condascending "you don't need any jquery for that :)" - you could put "this is vanilla javascript not jquery" but as it is, sounds very rude and a bit tackky - apologies, I normally include the reason in the edit (like with the snippet edit). Also, putting the answer first before code can make it easier to find in search / read the answer. – freedomn-m May 30 '20 at 10:13
  • I find "this is vanilla javascript not jquery" a lot more condescending than my answer :P – Marcin Wanago May 30 '20 at 10:14
  • Any answer with ":)" is condescending – freedomn-m May 30 '20 at 10:17
  • Most people here don't seem to know the / that there is a difference – freedomn-m May 30 '20 at 10:18
  • Still, could do with converting to a snippet to show it working and putting the answer first rather than last. – freedomn-m May 30 '20 at 10:18