How to add parameters to a URL that already contains other parameters and maybe an anchor

后端 未结 9 778
逝去的感伤
逝去的感伤 2020-12-05 19:36

I\'m wondering how I can add a new parameter to an existing url. The problem is: the url may also contain an anchor.

For example:

http://www.example         


        
9条回答
  •  盖世英雄少女心
    2020-12-05 20:26

    You can use this JS lib called URI.JS

    // mutating URLs
    URI("http://example.org/foo.html?hello=world")
        .username("rodneyrehm") 
            // -> http://rodneyrehm@example.org/foo.html?hello=world
        .username("") 
            // -> http://example.org/foo.html?hello=world
        .directory("bar")
            // -> http://example.org/bar/foo.html?hello=world
        .suffix("xml")    
            // -> http://example.org/bar/foo.xml?hello=world
        .hash("hackernews")
            // -> http://example.org/bar/foo.xml?hello=world#hackernews
        .fragment("")
            // -> http://example.org/bar/foo.xml?hello=world
        .search("") // alias of .query()
            // -> http://example.org/bar/foo.xml
        .tld("com")
            // -> http://example.com/bar/foo.xml
        .search({ foo: "bar", hello: ["world", "mars"] });
            // -> http://example.com/bar/foo.xml?foo=bar&hello=world&hello=mars
    

    or

    URI("?hello=world")
        .addSearch("hello", "mars")
            // -> ?hello=world&hello=mars
        .addSearch({ foo: ["bar", "baz"] })
            // -> ?hello=world&hello=mars&foo=bar&foo=baz
        .removeSearch("hello", "mars")
            // -> ?hello=world&foo=bar&foo=baz
        .removeSearch("foo")
            // -> ?hello=world
    

提交回复
热议问题