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.
This question is related to
javascript
file
input
escaping
backslash
Slightly hacky, but it works:
const input = '\text';_x000D_
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();_x000D_
_x000D_
console.log({ input, output });_x000D_
// { input: '\text', output: '\\text' }
_x000D_
Add an input id to the element and do something like that:
document.getElementById('inputId').value.split(/[\\$]/).pop()
Escape the backslash character.
foo.split('\\')
I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
Source: Stackoverflow.com