Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript finding part of a string

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!

like image 327
lightray22 Avatar asked Jan 25 '26 22:01

lightray22


2 Answers

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.

like image 130
Vivin Paliath Avatar answered Jan 27 '26 11:01

Vivin Paliath


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);

JS Fiddle demo.

like image 27
David Thomas Avatar answered Jan 27 '26 12:01

David Thomas