Reputation: 448
I'm not very used to Javascript so I'm having trouble manipulating strings...
If I have something like /folder1/folder2/folder3/ , how do I parse it so I end up with just the current folder, e.g. "folder3" ?
Thanks!
Upvotes: 2
Views: 131
Reputation: 95518
var folderName = str.match(/(folder\d+)\/$/)[1];
Should do it.
Explanation of the regex:
( -> 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.
The reason we are selecting the second element of the array (at index 1) is because the first element contains the complete string that was matched. This is not what we want; we just want the capture group. We only have one group that we captured, and so that is the second element.
Upvotes: 3
Reputation: 253318
Well, just because it's an option (though not necessarily sane):
var string = '/folder1/folder2/folder3/',
last = string.replace(/\//g,' ').trim().split(/\s/).pop();
console.log(last);
Upvotes: 2
Reputation: 1834
You can write the following:
var myString = '/fold1/fold2/fold3';
var myArray = myString.split('/');
var last_element = myArray[myArray.length - 1];
See the doc split
Upvotes: 0
Reputation: 21830
The split
function transform your string into an array using the supplied parameter as a delimiter.
Therefore:
var parts = "/folder1/folder2/folder3/".split("/");
Will result in parts
being equal to:
["", "folder1", "folder2", "folder3", ""]
You could then access each item using:
parts[0] // returns ''
parts[1] // returns 'folder1'
parts[2] // returns 'folder2'
.. and so on. Read more on split here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
Upvotes: 1
Reputation: 318212
var str = "/folder1/folder2/folder3/",
folder = str.substring(0, str.length - 1).split('/').pop();
Upvotes: 1
Reputation: 1908
You can use the split
function to retrieve all subpaths:
var path = '/folder1/folder2/folder3/';
var paths = path.split('/');
var pathNeeded = paths[paths.length - 2];
Upvotes: 1
Reputation: 177956
How stable is the format of that string? With a trailing slash you will need the next to last item
var parts = URL.split("/"); alert(parts[parts.length-2]);
Upvotes: 1