Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping backslash in string - javascript

I need to show the name of the currently selected file (in <input type="file"> element).

Everything is fine, the only problem is I'm getting this kind of string "C:\fakepath \typog_rules.pdf" (browset automatically puts this as value for the input element).

When I try to split the string by '\' or '\\' it fails because of unescaped slashes. Attempts to match/replace slashes fails too. Is there a way around this? I need this to work at least in Opera and IE (because in other browsers I can use FileReader)

E.G. I'm getting "C:\fakepath\typog_rules.pdf" as input and want to get "typog_rules.pdf" as output.

like image 803
Max Avatar asked Dec 23 '11 16:12

Max


People also ask

How do you escape a backslash in JavaScript?

The backslash() is an escape character in JavaScript. The backslash \ is reserved for use as an escape character in JavaScript. To escape the backslash in JavaScript use two backslashes.

How do you escape a backslash in a string?

The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.

How do you escape characters in a string JavaScript?

Javascript uses '\' (backslash) in front as an escape character. To print quotes, using escape characters we have two options: For single quotes: \' (backslash followed by single quote) For double quotes: \” (backslash followed by double quotes)

How do you write slash in JavaScript?

The backslash ( \ ) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).


Video Answer


2 Answers

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.
string = string.split("\\"); 

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

like image 190
Rob W Avatar answered Sep 24 '22 00:09

Rob W


I think this is closer to the answer you're looking for:

<input type="file">  $file = $(file); var filename = fileElement[0].files[0].name; 
like image 43
Himerzi Avatar answered Sep 27 '22 00:09

Himerzi