我不太习惯 Javascript,所以我在处理字符串时遇到了麻烦......
如果我有类似 /folder1/folder2/folder3/ 的东西,我该如何解析它,所以我最终只得到当前文件夹,例如 "folder3" ?
谢谢!
我不太习惯 Javascript,所以我在处理字符串时遇到了麻烦......
如果我有类似 /folder1/folder2/folder3/ 的东西,我该如何解析它,所以我最终只得到当前文件夹,例如 "folder3" ?
谢谢!
var folderName = str.match(/(folder\d+)\/$/)[1];
应该这样做。
正则表达式的解释:
( -> Start of capture group. We want a capture group because we just want
the folder name without the trailing slash.
folder -> Match the string "folder"
\d+ -> Match one or more digits
) -> End of capture group. This lets us capture strings of the form
"folderN", where N is a number.
\/ -> Escape forward slash. We have to escape this because / is used to
represent the start and end of a regex literal, in Javascript.
$ -> Match the end of the string.
我们选择数组的第二个元素(在索引 1 处)的原因是因为第一个元素包含匹配的完整字符串。这不是我们想要的;我们只想要捕获组。我们只捕获了一组,因此这是第二个元素。
好吧,只是因为它是一种选择(尽管不一定是理智的):
var string = '/folder1/folder2/folder3/',
last = string.replace(/\//g,' ').trim().split(/\s/).pop();
console.log(last);
该字符串的格式有多稳定?使用尾部斜杠,您将需要倒数第二项
var parts = URL.split("/"); alert(parts[parts.length-2]);
您可以使用该split
函数检索所有子路径:
var path = '/folder1/folder2/folder3/';
var paths = path.split('/');
var pathNeeded = paths[paths.length - 2];
var str = "/folder1/folder2/folder3/",
folder = str.substring(0, str.length - 1).split('/').pop();
该split
函数使用提供的参数作为分隔符将您的字符串转换为数组。
所以:
var parts = "/folder1/folder2/folder3/".split("/");
将导致parts
等于:
["", "folder1", "folder2", "folder3", ""]
然后,您可以使用以下方式访问每个项目:
parts[0] // returns ''
parts[1] // returns 'folder1'
parts[2] // returns 'folder2'
.. 等等。在此处阅读有关拆分的更多信息:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
您可以编写以下内容:
var myString = '/fold1/fold2/fold3';
var myArray = myString.split('/');
var last_element = myArray[myArray.length - 1];
查看文档拆分