How can I change the last component of a url path?

前端 未结 7 854
一整个雨季
一整个雨季 2021-02-09 03:15
\"http://something.com:6688/remote/17/26/172\"

if I have the value 172 and I need to change the url to 175

\"http://something.com:6688/         


        
相关标签:
7条回答
  • 2021-02-09 03:47
    var url = "http://something.com:6688/remote/17/26/172"
    url = url.replace(/\/[^\/]*$/, '/175')
    

    Translation: Find a slash \/ which is followed by any number * of non slash characters [^\/] which is followed by end of string $.

    0 讨论(0)
  • 2021-02-09 03:56

    Split the String by / then change the last part and rejoin by /:

    var newnumber = 175;
    var url = "http://something.com:6688/remote/17/26/172";
    var segements = url.split("/");
    segements[segements.length - 1] = "" + newnumber;
    var newurl = segements.join("/");
    alert(newurl); 
    

    Try it!

    0 讨论(0)
  • 2021-02-09 03:57

    Depends on what you want to do.

    Actually change browser URL:
    If you actually want to push the browser to another URL you'll have to use window.location = 'http://example.com/175'.

    Change browser URL hash
    If you just want to change the hash you can simply use window.location.hash.

    Re-use the URL on links or similar
    If you want to reference a URL in links or similar, look into George's answer.

    0 讨论(0)
  • 2021-02-09 03:58

    new URL("175", "http://something.com:6688/remote/17/26/172").href

    This also works with paths, e.g.

    new URL("../27", "http://something.com:6688/remote/17/26/172").href"http://something.com:6688/remote/17/27"

    new URL("175/1234", "http://something.com:6688/remote/17/26/172").href"http://something.com:6688/remote/17/26/175/1234"

    new URL("/local/", "http://something.com:6688/remote/17/26/172").href"http://something.com:6688/local/"

    See https://developer.mozilla.org/en-US/docs/Web/API/URL/URL for details.

    0 讨论(0)
  • 2021-02-09 04:06

    //Alternative way.

    var str =  window.location.href;
    var lastIndex = str.lastIndexOf("/");
    var path = str.substring(0, lastIndex);
    var new_path = path + "/new_path";
    window.location.assign(new_path);
    
    0 讨论(0)
  • 2021-02-09 04:07

    Split the String by /, remove the last part, rejoin by /, and add the new path

    newurl = url.split('/').slice(0,-1).join('/')+'/175'
    
    0 讨论(0)
提交回复
热议问题