0

suppose we have this URL "/user/id" .

let url = "/user/id"

so I need to split this urls and make an individual url . somethig like this:

["/", "/user", "/user/id"]

I can split this with .split("/").I think I need some forEach() after spliting but I cant get it right.

1
  • 1
    Please provide the code of what you have tried. Commented Apr 23, 2019 at 12:40

2 Answers 2

3

Actually it is way easier if you use indexOf to find the slashes and .slice to get the parts:

 const result = ["/"];
  let pos = 1;

 while(true) {
   pos = url.indexOf("/", pos + 1);
   if(pos < 0) break;
   result.push(url.slice(0, pos + 1));
 } 

 result.push(url);

Or the "functional approach" would be:

 url.split("/").map((_, i, arr) => arr.slice(0, i + 1).join("/") || "/");
Sign up to request clarification or add additional context in comments.

3 Comments

why haven't you used directly while(pos >= 0) instead of a break?
Well I could use that and do (pos + 1) || url.length, but I prefer the more readable version.
If it works, that's the most important I guess, but it reminds me my BASIC years, with such things as GOTO :D I would probably used split and a basic for loop for that though
1

For-loop solution:

https://jsfiddle.net/c9asnfw4/1/

let url = '/user/id', 
    result = ['/'],
    parts = url.split('/'); 

for(let i = 1; i < parts.length; i++) { // Skip first /
    const part = parts[i];

    if(i === 1) { // Start slash is already existing
        result.push(result[i-1] + part);
    } else if(i > 1) {
        result.push(result[i-1] + '/' + part);
    }
}

Output

(3) ["/", "/user", "/user/id"]


EDIT: Slightly shortened:

let url = '/user/id', 
    result = ['/'],
    parts = url.split('/'); 

for(let i = 1; i < parts.length; i++) { // Skip first /
    result.push( (result[i-1]) + (i > 1 ? '/' : '') + parts[i] );
}

https://jsfiddle.net/c9asnfw4/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.