Remove rest of string after the second to last index of

1k Views Asked by At

I'm relatively new to JS and pretty confused. I have a URL string: https://a/b/c/d/e/f. These are all dynamic characters and change often (could be https://x/s/g/e/h/d for example) In some cases I want to remove only f, in which I use LastIndexOf. In other cases I want to remove both the last and second to last EG: e/f. How can this be done successfully? I tried using a split but this just replaced the '/' with ',' for some reason.

working f example

var url = https://a/b/c/d/e/f
var new = url.substring(0, url.lastIndexOf('/') +1);

current split e/f example

var new = url.split('/')
console.log(new[new.length -2]);

This prints as: https:,,a,b,c,d,e,f,

5

There are 5 best solutions below

2
On BEST ANSWER

Here you are

const str = 'https://a/b/c/d/e/f'

function removeSegments(url, times) {
    const segments = url.split('/')
    return segments.slice(0, segments.length - times).join('/')
}

console.log(removeSegments(str, 1)) // 'https://a/b/c/d/e'
console.log(removeSegments(str, 2)) // 'https://a/b/c/d'
4
On

Here is one option, using regex replacement. To remove the final path only:

url = "https://a/b/c/d/e/f";
url = url.replace(/\/[^/]+$/mg, "");

To remove the final two paths:

url = "https://a/b/c/d/e/f";
url = url.replace(/\/[^/]+\/[^/]+$/mg, "");
0
On

You can easily do that using the URL API.

You need to split the pathname by / and then use Array#slice to take only the parts you want. Then join those again by /.

Here is an example:

var url = new URL('https://a/b/c/d/e/f');

console.log(
  url.origin +
  url.pathname.split('/').slice(0, -2).join('/')
);

0
On

split() creates an array of substrings that is passed in the split function. So when you write

url.split('/') it will create an array of substrings with / as delimeter.

The answer could be :

get the index of the element till when you want to remove your string by using :

var index = indexOf(x)

then pass it in the function.

var str1 = str.substr(0, index)

str1 will be your answer

0
On

You can use:

var num;
for ( var i=0; i< num; i++) {
    url= url.substring(0, url.lastIndexOf('/'));
}