Javascript:使用当前URL中的变量来创建和打开新的URL

Javascript: Using variables from current URL to create and open new URL

本文关键字:URL 创建 变量 Javascript      更新时间:2023-09-26

我有一个当前的网址,如下所示:

http://example?variables1=xxxx&example&variables2=yyyyy

我想使用变量 1 和变量 2 创建一个新 URL 并打开这个新 URL:

http://example?variables3=variables1&example&variables4=variables2

我希望有人可以帮助我解决这个问题:)

您需要从第一个 URL 解析所需的查询参数,并使用字符串添加来创建第二个 URL。

您可以使用此代码从 URL 获取特定查询参数。 如果你使用它,你可以得到变量 1 和变量 2,如下所示:

var variables1 = getParameterByName("variables1");
var variables2 = getParameterByName("variables2");

然后,您可以使用它们来构建您的新 URL。

newURL = "http://example.com/?variables1=" + 
    encodeURIComponent(variables1) + 
    "&someOtherStuff=foo&variables2=" + 
    encodeURIComponent(variables2);

因为我不完全明白需要改变什么,这是我最好的尝试*,使用其他答案和在线资源的混搭。

// the original url
// will most likely be window.location.href
var original = "http://example?variables1=xxxx&example&variables2=yyyyy";
// the function to pull vals from the URL
var getParameterByName = function(name, uri) {
    name = name.replace(/['[]/, "'''[").replace(/[']]/, "''']");
    var regexS = "[''?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(uri);
    if(results == null) return "";
    else return decodeURIComponent(results[1].replace(/'+/g, " "));
};
// so, to get the vals from the URL
var variables1 = getParameterByName('variables1', original); // xxxxx
var variables2 = getParameterByName('variables2', original); // yyyyy
// then to construct the new URL
var newURL =  "http://" + window.location.host;
    newURL += "?" + "variables3=" + variables1;
    newURL += "&example&"; // I don't know what this is ...
    newURL += "variables4=" + variables2;
// the value should be something along the lines of
// http://example?variables3=xxxx&example&variables4=yyyy

*所有这些都未经测试。