javascript查找字符串的一部分

时间:2013-03-22 21:12:26

标签: javascript string parsing

我不习惯Javascript,所以我在操作字符串时遇到了麻烦......

如果我有像/ folder1 / folder2 / folder3 /这样的东西,我如何解析它,所以我最终只得到当前文件夹,例如“folder3”?

谢谢!

7 个答案:

答案 0 :(得分: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处)的原因是因为第一个元素包含匹配的完整字符串。这不是我们想要的;我们只想要捕获组。我们只捕获了一个组,因此这是第二个元素。

答案 1 :(得分:2)

嗯,只是因为它是一个选项(虽然不一定是理智的):

var string = '/folder1/folder2/folder3/',
    last = string.replace(/\//g,' ').trim().split(/\s/).pop();
    console.log(last);

JS Fiddle demo

答案 2 :(得分:1)

该字符串的格式有多稳定? 使用尾部斜杠,您将需要最后一个项目

var parts = URL.split("/"); alert(parts[parts.length-2]);

答案 3 :(得分:1)

您可以使用split函数检索所有子路径:

var path = '/folder1/folder2/folder3/';
var paths = path.split('/');
var pathNeeded = paths[paths.length - 2];

Working example

答案 4 :(得分:1)

var str    = "/folder1/folder2/folder3/",
    folder = str.substring(0, str.length - 1).split('/').pop();

FIDDLE

答案 5 :(得分:1)

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

答案 6 :(得分:0)

您可以写下以下内容:

var myString = '/fold1/fold2/fold3';
var myArray = myString.split('/');
var last_element = myArray[myArray.length - 1];

请参阅文档split