Escaping backslash in string - javascript

若如初见. 提交于 2019-11-26 06:03:14

问题


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.


回答1:


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.




回答2:


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

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;



回答3:


Escape the backslash character.

foo.split('\\')



回答4:


Add an input id to the element and do something like that:

document.getElementById('inputId').value.split(/[\\$]/).pop()



回答5:


Slightly hacky, but it works:

const input = '\text';
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();

console.log({ input, output });
// { input: '\text', output: '\\text' }


来源:https://stackoverflow.com/questions/8618374/escaping-backslash-in-string-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!