javascriptreactjslastindexof

Remove rest of string after the second to last index of


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,


Solution

  • 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'