我不太习惯 Javascript,所以我在处理字符串时遇到了问题...
如果我有类似/folder1/folder2/folder3/的东西,我该如何解析它以便我最终只得到当前文件夹,例如“文件夹 3”?
谢谢!
最佳答案
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 处)的原因是因为第一个元素包含匹配的完整字符串。这不是我们想要的;我们只想要捕获组。我们只有一个我们捕获的组,所以这是第二个元素。
关于javascript查找字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15579912/