You can, firstly, a split
string on a character/
to convert it to an array:
var split = '/root/hello/hello/world'.split('/')
-> ["", "root", "hello", "hello", "world"]
Then you can grab the penultimate element:
var result = split[split.length - 2]
... but you can check the length of the array first:
var result;
if (split.length >= 2)
result = split[split.length - 2]
source
share