转义字符串中的反斜杠 - javascript
我需要显示当前选定文件的名称(在 元素中)。
一切都很好,唯一的问题是我得到这种字符串“C:\fakepath \typog_rules.pdf”(浏览器自动将其作为输入元素的值)。
当我尝试按 '\'
或 '\\'
分割字符串时,它失败 这个问题吗?我需要这个至少在 Opera 和 IE 中工作(因为在其他浏览器中我可以使用 FileReader)。
因为未转义斜杠,尝试匹配/替换斜杠也失败了,有办法解决 “C:\fakepath\typog_rules.pdf”作为输入,并希望获得“typog_rules.pdf”作为输出。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
转义反斜杠字符。
Escape the backslash character.
我认为这更接近您正在寻找的答案:
I think this is closer to the answer you're looking for:
有点 hacky,但它有效:
Slightly hacky, but it works:
向元素添加一个输入 id 并执行类似的操作:
Add an input id to the element and do something like that:
出于安全原因,无法获取通过
元素引用的文件的真实完整路径。
这个问题已经提到过,并链接到有关此主题的其他 Stack Overflow 问题。
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.
在 JavaScript 中,反斜杠用于转义特殊字符,例如换行符 (
\n
)。如果要使用文字反斜杠,则必须使用双反斜杠。因此,如果要匹配两个反斜杠,则必须使用四个反斜杠。例如,
alert("\\\\")
将显示一个包含两个反斜杠的对话框。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.
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.