0
\$\begingroup\$

Is there a better way to do this using chaining?

var url = "www.mycompany.com/sites/demo/t1"
var x = url.split('/');
console.log(x);
var y = x.pop();
console.log(y,x);
var z = x.join("/");
console.log(z);

I tried something like but wouldn't work since pop just returns the last value and not the rest:

 parentUrl = self.attr('Url').split("/").pop().join("/"); 
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Dec 1, 2014 at 21:04
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

pop() mutates the underlying list: it removes the last item (and returns it).

It seems you're looking for slice:

"www.mycompany.com/sites/demo/t1".split('/').slice(0, -1).join('/')
// -> gives: "www.mycompany.com/sites/demo"

.slice(0, -1) gives the elements of the list from the start until the end minus one item.

However, this is a very poor solution to drop the last path element from a URL. In particular, splitting a string to an array, drop the last element and join the string again is inefficient. It would be better to use lastIndexOf to find the position of the last /, and then substr to extract the part of the string before the last /.

var s = "www.mycompany.com/sites/demo/t1";
s.substr(0, s.lastIndexOf('/'));
answered Dec 1, 2014 at 21:22
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.