我有一个像http://www.example.com/blah/th.html
这样的网址我需要一个javascript函数来从中获取'th'值。
我的所有网址都采用相同的格式(2个字母的文件名,扩展名为.html)。
我希望它是一个安全的功能,所以如果有人传入一个空网址,它就不会破坏。
我知道如何检查长度,但我应该检查是否为空?
答案 0 :(得分:111)
var filename = url.split('/').pop()
答案 1 :(得分:58)
为什么这么难?
var filename = url.split('/').pop().split('#')[0].split('?')[0];
答案 2 :(得分:20)
使用匹配功能。
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}
答案 3 :(得分:9)
与其他人类似,但是......我使用过Tom的简单脚本 - 单行,
那么你可以在任何地方使用文件名var:
http://www.tomhoppe.com/index.php/2008/02/grab-filename-from-window-location/
var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1);
答案 4 :(得分:5)
考虑URL查询和哈希标识符的正则表达式解决方案:
function fileNameFromUrl(url) {
var matches = url.match(/\/([^\/?#]+)[^\/]*$/);
if (matches.length > 1) {
return matches[1];
}
return null;
}
JSFiddle here。
答案 5 :(得分:2)
我将substring
功能与lastIndexOf
结合使用。这将允许包含句点的文件名,例如如果给定http://example.com/file.name.txt
,则file.name
与file
提供的答案不同。
function GetFilename(url)
{
if (url)
{
return url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
}
return "";
}
答案 6 :(得分:2)
那些不适用于长白网的像 的" /my/folder/questions.html#dssddsdsd托托= 33&安培; dududu = podpodpo" 强>
在这里,我希望得到" questions.html"。 所以一个可能的(慢)解决方案如下所示
fname=function(url)
{ return url?url.split('/').pop().split('#').shift().split('?').shift():null }
然后你可以测试在任何情况下你只得到文件名。
fname("/my/folder/questions.html#dssddsdsd?toto=33&dududu=podpodpo")
-->"questions.html"
fname("/my/folder/questions.html#dssddsdsd")
-->"questions.html"
fname("/my/folder/questions.html?toto=33&dududu=podpodpo")
"-->questions.html"
(and it works for null)
(我希望看到更快或更智能的解决方案)
答案 7 :(得分:2)
由于自定义代码往往会失败,因此我查阅了JavaScript URL
类。 ,,它会阻塞相对URL!另外,它没有属性来获取文件名。 不是史诗。
那里有一个 ,可以解决这个普遍的问题。 Behold URI.js。您只需要一个简单的语句,如下所示:
let file = new URI(url).filename()
然后,我们可以创建一个简单的函数,该函数执行null检查并删除文件扩展名:
function fileName(url) {
if (url === null || typeof url === 'undefined')
return ''
let file = new URI(url).filename() // File name with file extension
return file.substring(0, file.lastIndexOf('.')) // Remove the extension
}
这是一个包含测试用例的片段。除驱动路径外,所有情况均通过。
test('Dots in file name without URL', 'dotted.file.name.png', 'dotted.file.name')
test('Dots in file name with URL', 'http://example.com/file.name.txt', 'file.name')
test('Lengthy URL with parameters', '/my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo', 'filename')
test('URL with hash', '/my/folder/filename.html#dssddsdsd', 'filename')
test('URL with query strings', '/my/folder/filename.html?toto=33&dududu=podpodp', 'filename')
test('Hash after query string', 'http://www.myblog.com/filename.php?year=2019#06', 'filename')
test('Query parameter with file path character', 'http://www.example.com/filename.zip?passkey=1/2', 'filename')
test('Query parameter with file path character and hash', 'http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top', 'filename')
test('Asian characters', 'http://example.com/文件名.html', '文件名')
test('URL without file name', 'http://www.example.com', '')
test('Null', null, '')
test('Undefined', undefined, '')
test('Empty string', '', '')
test('Drive path name', 'C:/fakepath/filename.csv', 'filename')
function fileName(url) {
if (url === null || typeof url === 'undefined')
return ''
let file = new URI(url).filename() // File name with file extension
return file.substring(0, file.lastIndexOf('.')) // Remove the extension
}
function test(description, input, expected) {
let result = fileName(input)
let pass = 'FAIL'
if (result === expected)
pass = 'PASS'
console.log(pass + ': ' + description + ': ' + input)
console.log(' => "' + fileName(input) + '"')
}
<script src="https://cdn.jsdelivr.net/gh/medialize/URI.js@master/src/URI.js"></script>
结果
PASS: Dots in file name without URL: dotted.file.name.png
=> "dotted.file.name"
PASS: Dots in file name with URL: http://example.com/file.name.txt
=> "file.name"
PASS: Lengthy URL with parameters: /my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo
=> "filename"
PASS: URL with hash: /my/folder/filename.html#dssddsdsd
=> "filename"
PASS: URL with query strings: /my/folder/filename.html?toto=33&dududu=podpodp
=> "filename"
PASS: Hash after query string: http://www.myblog.com/filename.php?year=2019#06
=> "filename"
PASS: Query parameter with file path character: http://www.example.com/filename.zip?passkey=1/2
=> "filename"
PASS: Query parameter with file path character and hash: http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top
=> "filename"
PASS: Asian characters: http://example.com/文件名.html
=> "文件名"
PASS: URL without file name: http://www.example.com
=> ""
PASS: Null: null
=> ""
PASS: Undefined: undefined
=> ""
PASS: Empty string:
=> ""
FAIL: Drive path name: C:/fakepath/filename.csv
=> ""
如果您懒于编写自定义代码,并且不介意使用库来为您工作,那么此解决方案适合您。如果您想为该解决方案编写代码,则不适合您。
答案 8 :(得分:2)
将jQuery与URL plugin:
一起使用var file = jQuery.url.attr("file");
var fileNoExt = file.replace(/\.(html|htm)$/, "");
// file == "th.html", fileNoExt = "th"
答案 9 :(得分:2)
这应该适用于所有情况
function getFilenameFromUrl(url: string): string {
const pathname = new URL(url).pathname;
const index = pathname.lastIndexOf('/');
return (-1 !== index ? pathname.substring(index + 1) : pathname);
}
答案 10 :(得分:1)
实际上,标记的答案是正确的,但是如果第二个if
不满足该函数,则返回undefined
,我更喜欢这样写:
const getFileNameFromUrl = (url: string): string => {
if (url) {
const tmp = url.split('/');
const tmpLength = tmp.length;
return tmpLength ? tmp[tmpLength - 1] : '';
}
return '';
};
对于我的问题,我需要具有文件扩展名。
答案 11 :(得分:1)
<script type="text/javascript">
function getFileName(url){
var path = window.location.pathName;
var file = path.replace(/^.*\/(\w{2})\.html$/i, "$1");
return file ? file : "undefined";
}
</script>
答案 12 :(得分:1)
此答案仅适用于浏览器环境。不适合节点。
function getFilename(url) {
const filename = decodeURIComponent(new URL(url).pathname.split('/').pop());
if (!filename) return 'index.html'; // some default filename
return filename;
}
function filenameWithoutExtension(filename) {
return filename.replace(/^(.+?)(?:\.[^.]*)?$/, '$1');
}
对于浏览器不支持new URL
,您可能需要:
var a = document.createElement('a');
a.href = url;
var pathname = a.pathname;
这是两个功能:
对于解析URL,新的URL
对象应该是最佳选择。另请注意,URL并不总是包含文件名。
注意:此函数尝试从URL解析文件名。但它不保证文件名有效且适合使用:
:
,大多数操作系统中的\0
,...); 答案 13 :(得分:1)
对于节点和浏览器,基于@pauls答案,但解决了哈希和防御性更高的问题:
export function getFileNameFromUrl(url) {
const hashIndex = url.indexOf('#')
url = hashIndex !== -1 ? url.substring(0, hashIndex) : url
return (url.split('/').pop() || '').replace(/[\?].*$/g, '')
}
少数情况:
describe('getFileNameFromUrl', () => {
it('absolute, hash and no extension', () => {
expect(getFileNameFromUrl(
'https://foo.bar/qs/bar/js-function-to-get-filename-from-url#comment95124061_53560218'))
.toBe('js-function-to-get-filename-from-url')
})
it('relative, extension and parameters', () => {
expect(getFileNameFromUrl('../foo.png?ar=8')).toBe('foo.png')
})
it('file name with multiple dots, hash with slash', () => {
expect(getFileNameFromUrl('questions/511761/js-function.min.js?bar=9.9&y=1#/src/jjj?=9.9')).toBe('js-function.min.js')
})
})
答案 14 :(得分:0)
这应该可以处理您抛出的任何内容(绝对 URL、相对 URL、复杂的 AWS URL 等)。如果文件名和默认值都不存在,它包括一个可选的默认值或使用伪随机字符串。
function parseUrlFilename(url, defaultFilename = null) {
let filename = new URL(url, "https://example.com").href.split("#").shift().split("?").shift().split("/").pop(); //No need to change "https://example.com"; it's only present to allow for processing relative URLs.
if(!filename) {
if(defaultFilename) {
filename = defaultFilename;
//No default filename provided; use a pseudorandom string.
} else {
filename = Math.random().toString(36).substr(2, 10);
}
}
return filename;
}
@hayatbiralem nailing the order of the split()
s 的道具。
答案 15 :(得分:0)
除了现有的答案之外,我还建议使用 URL() constructor
(在浏览器和 Node.js 中都有效),因为您可以确定您的 URL 是有效的:
const url = 'https://test.com/path/photo123.png?param1=1¶m2=2#hash';
let filename = '';
try {
filename = new URL(url).pathname.split('/').pop();
} catch (e) {
console.error(e);
}
console.log(`filename: ${filename}`);
答案 16 :(得分:0)
url? url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.')):''
null
或undefined
,则结果为 ''
。它允许文件名具有多个句点!
不询问,但您也可以使用不带'/'和'。'的查询字符串。
这是Abhishek Sharma的正确答案,所以我给了他赞成。如此巧妙且极少的单线-我在那儿看到了:)
答案 17 :(得分:0)
这就是答案!
<?xml version="1.0" encoding="utf-8"?>
<cCSVArray xmlns:d="http://www.kuju.com/TnT/2003/Delta" d:version="1.0" d:id="1">
<CSVItem>
<cCSVItem d:id="2">
<X d:type="sFloat32">0</X>
<Y d:type="sFloat32">0</Y>
<Name d:type="cDeltaString">(80000415004</Name>
</cCSVItem>
</CSVItem>
</cCSVArray>
var filename = url.split('/').pop().replace(/[\#\?].*$/,'').split('.').shift()
删除路径url.split('/').pop()
的字符串 .replace(/[\#\?].*$/,'')
删除所有扩展名为什么答案没有回答这个问题? 示例:.split('.').shift()
http://www.example.com/blah/th.html#1234?xxx=555
http:
www.example.com
上拆分--- pop ---> blah
th.html#1234?xxx=555
th.html
<--- shift --- th
有人问这个 答案 18 :(得分:0)
function getFileName(url) {
// Remove the QueryString
url = url.replace(/\?.*$/, '');
// Extract the last part
return url.split('/').pop();
}
答案 19 :(得分:0)
试试这个
url.substring(url.lastIndexOf('/')+1, url.length)
答案 20 :(得分:0)
如果查询字符串包含&#34; /&#34;
,LastIndexOf(&#34; /&#34;)方法本身就会失败我们都知道他们应该&#34;应该&#34;被编码为%2F
,但只会有一个未转义的值导致问题。
此版本正确处理查询字符串中的内容,并且不依赖于网址中的。
function getPageName() {
//#### Grab the url
var FullUrl = window.location.href;
//#### Remove QueryStrings
var UrlSegments = FullUrl.split("?")
FullUrl = UrlSegments[0];
//#### Extract the filename
return FullUrl.substr(FullUrl.lastIndexOf("/") + 1);
}
答案 21 :(得分:0)
与@ user2492653建议的相似,如果你想要的只是Firefox提供给你的文件的名称,那么你就是split()方法,它将字符串分解成一个组件数组,然后你只需要它就可以了抓住最后一个指数。
var temp = url.split("//");
if(temp.length > 1)
return temp[temp.length-1] //length-1 since array indexes start at 0
这基本上会将C:/fakepath/test.csv分解为{“C:”,“fakepath”,“test.csv”}
答案 22 :(得分:-1)
来自How to get the file name from a full path using JavaScript?
var filename = fullPath.replace(/^.*[\\\/]/, '')