For a given path, for example - abc/def/hijkl/mno.txt how to extract all the paths like below
abc
abc/def
abc/def/hijkl
abc/def/hijkl/mno.txt
Like an array with actual path and all the sub paths till the root path.
I've tried the getting this with regex but I do not find a way to match every occurrence of / from the beginning of the string.
Below is the regex I've tried
(.*?)?\/+
Is there any way to get this output with regex in javascript
You don't need Regexp for this.
You can just split your string into an array using split, then reconstitute slices of that array back into paths using join.
const path = "abc/def/hijkl/mno.txt";
const segments = path.split('/');
const paths = segments.map((s, i) => segments.slice(0, i + 1).join('/'))
console.log(paths)
You can split your string by / and append the array list as you desire:
Example:
const str = `abc/def/hijkl/mno.txt`;
let array = str.split('/');
res=""
len=array.length;
for (let i = 0; i < len; i++) {
res+=array[i];
console.log(res);
if(i<len-1)
res+="/";
}