转义字符串中的反斜杠 - javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8618374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping backslash in string - javascript
提问by Max
I need to show the name of the currently selected file (in <input type="file">
element).
我需要显示当前选定文件的名称(在<input type="file">
元素中)。
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).
一切都很好,唯一的问题是我得到了这种字符串“C:\fakepath\typog_rules.pdf”(浏览器自动将其作为输入元素的值)。
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)
当我尝试拆分字符串时,'\'
或者'\\'
由于未转义的斜杠而失败。尝试匹配/替换斜线也失败了。有没有解决的办法?我需要它至少在 Opera 和 IE 中工作(因为在其他浏览器中我可以使用 FileReader)
E.G. I'm getting "C:\fakepath\typog_rules.pdf" as input and want to get "typog_rules.pdf" as output.
EG 我得到“C:\fakepath\typog_rules.pdf”作为输入并希望得到“typog_rules.pdf”作为输出。
回答by Rob W
For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" />
element.
出于安全原因,不可能获得通过<input type="file" />
元素引用的文件的真实完整路径。
This questionalready mentions, and links to other Stack Overflow questions regarding this topic.
这个问题已经提到,并链接到关于这个主题的其他 Stack Overflow 问题。
Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.以前的答案,作为通过标题、标签和问题访问此页面的未来访问者的参考。
必须转义反斜杠。
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.
在 JavaScript 中,反斜杠用于转义特殊字符,例如换行符 ( \n
)。如果要使用文字反斜杠,则必须使用双反斜杠。
So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\")
will show a dialog containing two backslashes.
因此,如果要匹配两个反斜杠,则必须使用四个反斜杠。例如,alert("\\\\")
将显示一个包含两个反斜杠的对话框。
回答by Himerzi
I think this is closer to the answer you're looking for:
我认为这更接近您正在寻找的答案:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
回答by Quentin
Escape the backslash character.
转义反斜杠字符。
foo.split('\')
回答by Yifat Biezuner
Add an input id to the element and do something like that:
向元素添加输入 id 并执行以下操作:
document.getElementById('inputId').value.split(/[\$]/).pop()
回答by Ashley Williams
Slightly hacky, but it works:
有点hacky,但它有效:
const input = '\text';
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();
console.log({ input, output });
// { input: '\text', output: '\text' }