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("/"); 
\$\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('/'));
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.