Remove rest of string after the second to last index of












1















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,










share|improve this question























  • split just splits the string into an array of strings and not replace it

    – Shubham Khatri
    Nov 16 '18 at 11:36






  • 1





    You probably shouldn't use new as a variable name

    – Pete
    Nov 16 '18 at 11:43











  • @Pete thanks, that was just a quick name used for the purpose of the question

    – Uciebila
    Nov 16 '18 at 11:53
















1















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,










share|improve this question























  • split just splits the string into an array of strings and not replace it

    – Shubham Khatri
    Nov 16 '18 at 11:36






  • 1





    You probably shouldn't use new as a variable name

    – Pete
    Nov 16 '18 at 11:43











  • @Pete thanks, that was just a quick name used for the purpose of the question

    – Uciebila
    Nov 16 '18 at 11:53














1












1








1








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,










share|improve this question














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,







javascript reactjs lastindexof






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 11:33









UciebilaUciebila

5518




5518













  • split just splits the string into an array of strings and not replace it

    – Shubham Khatri
    Nov 16 '18 at 11:36






  • 1





    You probably shouldn't use new as a variable name

    – Pete
    Nov 16 '18 at 11:43











  • @Pete thanks, that was just a quick name used for the purpose of the question

    – Uciebila
    Nov 16 '18 at 11:53



















  • split just splits the string into an array of strings and not replace it

    – Shubham Khatri
    Nov 16 '18 at 11:36






  • 1





    You probably shouldn't use new as a variable name

    – Pete
    Nov 16 '18 at 11:43











  • @Pete thanks, that was just a quick name used for the purpose of the question

    – Uciebila
    Nov 16 '18 at 11:53

















split just splits the string into an array of strings and not replace it

– Shubham Khatri
Nov 16 '18 at 11:36





split just splits the string into an array of strings and not replace it

– Shubham Khatri
Nov 16 '18 at 11:36




1




1





You probably shouldn't use new as a variable name

– Pete
Nov 16 '18 at 11:43





You probably shouldn't use new as a variable name

– Pete
Nov 16 '18 at 11:43













@Pete thanks, that was just a quick name used for the purpose of the question

– Uciebila
Nov 16 '18 at 11:53





@Pete thanks, that was just a quick name used for the purpose of the question

– Uciebila
Nov 16 '18 at 11:53












5 Answers
5






active

oldest

votes


















2














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'





share|improve this answer
























  • This was the easiest and cleanest way for me to replicate this into my code, thank you

    – Uciebila
    Nov 16 '18 at 11:52











  • Glad it helped you!

    – Nurbol Alpysbayev
    Nov 16 '18 at 11:54



















1














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, "");





share|improve this answer
























  • Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

    – Uciebila
    Nov 16 '18 at 11:45











  • @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

    – Tim Biegeleisen
    Nov 16 '18 at 13:36











  • From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

    – Uciebila
    Nov 16 '18 at 13:57











  • Strange. It is too bad that your framework is limiting what you can and cannot do.

    – Tim Biegeleisen
    Nov 16 '18 at 13:58





















0














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('/')
);








share|improve this answer































    0














    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






    share|improve this answer































      0














      You can use:



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





      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337032%2fremove-rest-of-string-after-the-second-to-last-index-of%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        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'





        share|improve this answer
























        • This was the easiest and cleanest way for me to replicate this into my code, thank you

          – Uciebila
          Nov 16 '18 at 11:52











        • Glad it helped you!

          – Nurbol Alpysbayev
          Nov 16 '18 at 11:54
















        2














        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'





        share|improve this answer
























        • This was the easiest and cleanest way for me to replicate this into my code, thank you

          – Uciebila
          Nov 16 '18 at 11:52











        • Glad it helped you!

          – Nurbol Alpysbayev
          Nov 16 '18 at 11:54














        2












        2








        2







        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'





        share|improve this 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'






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 11:39









        Nurbol AlpysbayevNurbol Alpysbayev

        4,0191327




        4,0191327













        • This was the easiest and cleanest way for me to replicate this into my code, thank you

          – Uciebila
          Nov 16 '18 at 11:52











        • Glad it helped you!

          – Nurbol Alpysbayev
          Nov 16 '18 at 11:54



















        • This was the easiest and cleanest way for me to replicate this into my code, thank you

          – Uciebila
          Nov 16 '18 at 11:52











        • Glad it helped you!

          – Nurbol Alpysbayev
          Nov 16 '18 at 11:54

















        This was the easiest and cleanest way for me to replicate this into my code, thank you

        – Uciebila
        Nov 16 '18 at 11:52





        This was the easiest and cleanest way for me to replicate this into my code, thank you

        – Uciebila
        Nov 16 '18 at 11:52













        Glad it helped you!

        – Nurbol Alpysbayev
        Nov 16 '18 at 11:54





        Glad it helped you!

        – Nurbol Alpysbayev
        Nov 16 '18 at 11:54













        1














        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, "");





        share|improve this answer
























        • Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

          – Uciebila
          Nov 16 '18 at 11:45











        • @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

          – Tim Biegeleisen
          Nov 16 '18 at 13:36











        • From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

          – Uciebila
          Nov 16 '18 at 13:57











        • Strange. It is too bad that your framework is limiting what you can and cannot do.

          – Tim Biegeleisen
          Nov 16 '18 at 13:58


















        1














        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, "");





        share|improve this answer
























        • Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

          – Uciebila
          Nov 16 '18 at 11:45











        • @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

          – Tim Biegeleisen
          Nov 16 '18 at 13:36











        • From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

          – Uciebila
          Nov 16 '18 at 13:57











        • Strange. It is too bad that your framework is limiting what you can and cannot do.

          – Tim Biegeleisen
          Nov 16 '18 at 13:58
















        1












        1








        1







        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, "");





        share|improve this answer













        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, "");






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 11:38









        Tim BiegeleisenTim Biegeleisen

        222k1390143




        222k1390143













        • Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

          – Uciebila
          Nov 16 '18 at 11:45











        • @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

          – Tim Biegeleisen
          Nov 16 '18 at 13:36











        • From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

          – Uciebila
          Nov 16 '18 at 13:57











        • Strange. It is too bad that your framework is limiting what you can and cannot do.

          – Tim Biegeleisen
          Nov 16 '18 at 13:58





















        • Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

          – Uciebila
          Nov 16 '18 at 11:45











        • @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

          – Tim Biegeleisen
          Nov 16 '18 at 13:36











        • From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

          – Uciebila
          Nov 16 '18 at 13:57











        • Strange. It is too bad that your framework is limiting what you can and cannot do.

          – Tim Biegeleisen
          Nov 16 '18 at 13:58



















        Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

        – Uciebila
        Nov 16 '18 at 11:45





        Thanks for this, when I add the reg ex in, on replace(/**** it gives an error reading: unterminated Regular expression literal.

        – Uciebila
        Nov 16 '18 at 11:45













        @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

        – Tim Biegeleisen
        Nov 16 '18 at 13:36





        @Uciebila Your comment makes no sense, and I can only comment that my answer solved your problem in fewer lines of code than the answer you accepted.

        – Tim Biegeleisen
        Nov 16 '18 at 13:36













        From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

        – Uciebila
        Nov 16 '18 at 13:57





        From some research I found thatbecause my code is within a react app, it is a .js and not a .jsx. Which meant that using the above code threw an error that wouldnt be fixed until I changed my file extension, which would break the react app. With the way I added the accepted answer into my code it only needed two lines

        – Uciebila
        Nov 16 '18 at 13:57













        Strange. It is too bad that your framework is limiting what you can and cannot do.

        – Tim Biegeleisen
        Nov 16 '18 at 13:58







        Strange. It is too bad that your framework is limiting what you can and cannot do.

        – Tim Biegeleisen
        Nov 16 '18 at 13:58













        0














        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('/')
        );








        share|improve this answer




























          0














          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('/')
          );








          share|improve this answer


























            0












            0








            0







            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('/')
            );








            share|improve this answer













            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('/')
            );








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

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





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

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






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 16 '18 at 11:40









            31piy31piy

            17.2k52342




            17.2k52342























                0














                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






                share|improve this answer




























                  0














                  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






                  share|improve this answer


























                    0












                    0








                    0







                    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






                    share|improve this answer













                    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







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 11:43









                    vertikavertika

                    870419




                    870419























                        0














                        You can use:



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





                        share|improve this answer






























                          0














                          You can use:



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





                          share|improve this answer




























                            0












                            0








                            0







                            You can use:



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





                            share|improve this answer















                            You can use:



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






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 16 '18 at 11:50









                            SamTebbs33

                            3,86031632




                            3,86031632










                            answered Nov 16 '18 at 11:47









                            simonasimona

                            12




                            12






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337032%2fremove-rest-of-string-after-the-second-to-last-index-of%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Academy of Television Arts & Sciences

                                L'Équipe

                                1995 France bombings