js function to get filename from url
var filename = url.split('/').pop()
How to extract the filename of the URL of the current document path in JavaScript?
If you're looking for the last item in the path, try this:
var current_path = window.location.pathname.split('/').pop();
This:window.location.pathname
will give you something like:"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"
Then the .split()
will split the string into an Array, and .pop()
will give you the last item in the Array. jQuery: extract file name from an href link when adding download attribute
Calling jQuery("a").attr("download", "downloadedfile.dxf");
in a .each()
updates ALL the elements' download
attribute multiple times, not just the one you're trying to update.
You'll have to pass in the element into your .each
callback, or use $(this)
to keep refer to the "current" element in the collection you're iterating over.
jQuery('a[href*=".dxf"]').each(function(i, $elem) {
var pathname;
if (typeof URL !== 'undefined') {
var url = new URL($elem.attr('href'));
// Note: Using URL.pathname strips off the #hash and ?foo=bar arguments
// e.g. 'https://example.com/foo/bar/baz.xls?id=2&a=b#hash'
// -> 'baz.xls'
pathname = url.pathname.split('/').pop();
} else {
// must be IE11 or older (~1.38% user share as of 2020-07-08)
pathname = $elem.attr('href');
}
var filename = pathname.split('/').pop();
$elem.attr("download", filename);
});
Note: The URL
class isn't supported in IE 11 or older. Get filename from URL using JavaScript
Try adding this line to the end of your code sample:
fileName = fileName.replace(/[\#\?].*$/,''); // strips hashes, too
String.replace on MDN Get current file name from a url using javascript/jquery when only folder path is known
If you only have the path in the URL, then you cannot get the filename from it - not using jQuery, not using any other client-side method. This is because only the server that sends this file knows what this file is. Specifically, in the web server configuration, there's a directive, which indicates what filename to search for if only the directory name is specified. For example, in apache this can be
DirectoryIndex index.html index.php home.htm
This tells the server that for requests with only a directory name the server will attempt to serve file index.html
from that directory; if it doesn't exist, then index.php
; if that also doesn't exist then home.htm
. If that one also doesn't exist, then the behaviour depends on other configuration options. Other web server software has similar configuration options.Hence, when you send a request like http://www.yoursite.com/folder/ to a server, only that server will know what file is actually used.
Get File Name from list of URL's - Google Drive
Your getIdFromLink()
function should work just fine as long as the files have not been shared in such a way that they require a resource key as well.
To work with resource keys, use DriveApp.getFileByIdAndResourceKey(), like this:
function getFileNamesByLink() {
const sheet = SpreadsheetApp.getActiveSheet();
const sourceRange = sheet.getRange('AE2:AL');
const targetRange = sheet.getRange('AM2');
const fileNames = sourceRange.getValues()
.map(row => row.map(link => getFileNameFromLink_(link)));
targetRange
.offset(0, 0, fileNames.length, fileNames[0].length)
.setValues(fileNames);
}
function getFileNameFromLink_(link) {
if (!link) {
return null;
}
const fileId = getIdFromLink_(link);
if (!fileId) {
return NaN;
}
let file;
try {
file = DriveApp.getFileById(fileId);
} catch (error) {
try {
file = DriveApp.getFileByIdAndResourceKey(fileId, getResourceKeyFromLink_(link));
} catch (error) {
return NaN;
}
}
return file.getName();
}
function getIdFromLink_(link) {
const match = String(link).match(/file\/d\/([-\w]+)/i);
return match ? match[1] : null;
}
function getResourceKeyFromLink_(link) {
const match = String(link).match(/resourcekey=([-\w]+)/i);
return match ? match[1] : null;
}
Note that the script may time out if you have thousands of links. If that happens, process the links in a piecemeal fashion, or see if the Advanced Drive Service works for you. Get file name with Jquery
This is some simple example. I hope this will help to you:
$(document).ready(function() {
$("#image_file").on("change", function() {
$("#select_file").html(this.value);
});
});
Edit: Only now I realized what the problem is.
So this is the code:
$(".upload-btn").one("click", function _handler(event) {
_handler.oldContext = this;
var _file = $(this).find("input[type='file']").one("change", function() {
var oldContext = $(_handler.oldContext);
oldContext.find("span#select_file").html(this.value);
$(this).attr("display", "none");
oldContext.one("click", _handler);
});
_file.attr("display","block").trigger("click");
event.stopPropagation();
});
and this is working jsfiddle:https://jsfiddle.net/qpo8dwf9/33/
Edit2: This is working example with two inputs and attach listeners on document ready.
https://jsfiddle.net/qpo8dwf9/38/
Edit3: There is issues under Chrome and Chromium with fakepath. This is the last version.
https://jsfiddle.net/qpo8dwf9/49/
Getting just the filename from a path with JavaScript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
JQUERY AJAX find filename in response data
It seems you want to extract the file names from the calls to addRow.
Here's an example of how to extract them using a regular expression.
const findFiles = (text) => {
let matches = [];
let match;
let regex = /addRow\("(.*?)"/g;
while (match = regex.exec(text)) {
matches.push(match[1]);
}
return matches;
};
// instead of this example "text" use the result from your AJAX call
const text = `<script>onHasParentDirectory();</scri` + `pt><script>addRow("20220201221359.csv","20220201221359.csv",0,2959,"2.9 kB",1644181136,"06.02.22, 21:58:56");</scri` + `pt><script>addRow("20220206091030.csv","20220206091030.csv",0,2958,"2.9 kB",1644181136,"06.02.22, 21:58:56");</scri` + `pt><scri` + `pt>addRow("20220206135359.csv","20220206135359.csv",0,2959,"2.9 kB",1644181136,"06.02.22, 21:58:56");</scri` + `pt>`;
console.log(findFiles(text));
Related Topics
Using Fetch API to Access JSON
Why Are Exceptions Used for Rejecting Promises in Js
Javascript: Unicode String to Hex
How to Auto-Reload Files in Node.Js
Regular Expression to Match Exactly 5 Digits
Check If File Exists But Prevent 404 Error in Console from Showing Up
React Doesn't Reload Component Data on Route Param Change or Query Change
Detect 64-Bit or 32-Bit Windows from User Agent or JavaScript
How to Pass a Flag to Gulp to Have It Run Tasks in Different Ways
How to Bind to the Change Event of a Textarea in Jquery
Options for Testing Service Workers via Http
How to Parseint a String with Leading 0
JavaScript Get Object Key Name
Loading Backbone and Underscore Using Requirejs