在字符串中转义反斜杠 - javascript [英] Escaping backslash in string - javascript

查看:168
本文介绍了在字符串中转义反斜杠 - javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示当前所选文件的名称(在< input type =file> 元素中)。

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

一切都很好,唯一的问题是我得到这种字符串C:\fakepath
\typog_rules.pdf(自动浏览将此作为输入元素的值)。

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).

当我尝试将字符串拆分为'\''\\'由于未转义的斜杠而失败。匹配/替换斜杠的尝试也失败。有没有解决的办法?我需要这样工作至少在Opera和IE(因为在其他浏览器我可以使用FileReader)

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。我得到C:\fakepath\typog_rules.pdf作为输入,并希望得到typog_rules.pdf作为输出。

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

推荐答案

出于安全考虑,不可能通过< input type =file/> 元素。

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

此问题已经提及,并链接到有关此主题的其他Stack Overflow问题。

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("\\");

在JavaScript中,反斜杠用于转义特殊字符,如换行符( \\\
)。如果要使用文字反斜杠,则必须使用双反斜杠。

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.

因此,如果要匹配两个反斜杠,则必须使用四个反斜杠。例如, alert(\\\\\)将显示一个包含两个反斜杠的对话框。

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

这篇关于在字符串中转义反斜杠 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆