从标记中的href获取查询字符串参数

时间:2022-08-24 12:20:52

I have a page with a series of <a> links on it that look like this:

我有一个页面上有一系列链接,如下所示:

<a href="http://www.domain.com/page/other.jsf?fruit=apple&tree=pine&rock=sedimentary">click me</a>

These parameters manipulate the content for the eventual page linked to ("other.jsf") in minor ways.

这些参数以较小的方式操纵链接到(“other.jsf”)的最终页面的内容。

As part of an A/B/n test I want to change the parameters in the href based on user behaviour on the page containing the link. So, for example, I'd want to change the fruit parameter to "orange" before it was clicked.

作为A / B / n测试的一部分,我想根据包含链接的页面上的用户行为更改href中的参数。因此,例如,我想在点击之前将fruit参数更改为“orange”。

My problem is that the parameters change location in the string or may not exist at all for some links and the .param() function only appears to work on urls.

我的问题是参数更改了字符串中的位置,或者某些链接可能根本不存在,而.param()函数似乎只对URL有效。

So far (based on another question answer) I have this, but it doesn't account for the possibility that there may be no "end_pos" or if "fruit=" is missing from the href (though this second bit seems like an easier fix with an if undefined-type function):

到目前为止(基于另一个问题的答案)我有这个,但它没有考虑到可能没有“end_pos”或者如果href中缺少“fruit =”的可能性(虽然这第二位似乎更容易使用if undefined-type函数修复):

$('a').each(function () {
    if ($(this).attr('href').indexOf('other') > -1) {
        var hrefStr = $(this).attr('href');
        var start_pos = hrefStr.indexOf('fruit=') + 1;
        var end_pos = hrefStr.indexOf('&',start_pos); //works as long as fruit=apple is in the middle or front of the string
        var fruit = hrefStr.substring(start_pos,end_pos);
        ...
        //put modified href back in <a>
    }
});

My second problem is then identifying the same part of the original href to put the new string back into. I can probably get this after understanding the method for extracting it in the first place though.

我的第二个问题是识别原始href的相同部分以将新字符串放回。我可以在理解了首先提取它的方法之后得到这个。

I should also say I have no control over the .jsf pages other than via JavaScript

我还应该说除了通过JavaScript之外我无法控制.jsf页面

4 个解决方案

#1


1  

You could use Attribute Contains Selector [name*="value"] "a[href*=fruit]" to select a elements that contain "fruit" at href attribute, .attr(attributeName, function) , String.prototype.replace() to replace "apple" with "orange"

您可以使用Attribute Contains Selector [name * =“value”]“a [href * = fruit]”来选择在href属性中包含“fruit”的元素,.attr(attributeName,function),String.prototype.replace( )用“橙色”取代“苹果”

$("a[href*=fruit]").attr("href", function(_, href) {
  return href.replace(/apple/, "orange")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<a href="http://www.domain.com/page/other.jsf?fruit=apple&tree=pine&rock=sedimentary">click me</a>

#2


1  

I used this function to do that :

我用这个函数来做到这一点:

function getQueryParameters (str) {
  return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}

var queryParams = getQueryParameters(myUrl);

result :

结果:

{
    "fruit": "apple",
     ...
}

#3


1  

Heres a way I use to extract url parameters!

这是我用来提取url参数的一种方式!

var getUrlParameter = function(sParam,url) {
    var sPageURL = url;
    if(typeof(sPageURL) === 'undefined' || sPageURL == ''){
        sPageURL = decodeURIComponent(window.location.search.substring(1));
    }
    var sURLVariables = sPageURL.split('&'), sParameterName, i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURI(sParameterName[1]);
        }
    }
};

usage

用法

 getUrlParameter('fruit',url_after_question_mark);

Part 2 of your problem! If your parameters are known or atleast a known set you could always reconstruct the url with fresh values.

问题的第2部分!如果您的参数已知或至少是已知集合,则始终可以使用新值重建URL。

e.g. var params = ['fruit','tree','some_other','some_other2'];//superset of all possible parameters.

例如var params = ['fruit','tree','some_other','some_other2']; //所有可能参数的超集。

Now you could loop through this array and call getUrlParameter function with each of the parameter to see if it exists. If it exists reconstruct your url with fresh values.

现在,您可以遍历此数组并使用每个参数调用getUrlParameter函数以查看它是否存在。如果存在,则使用新值重建您的网址。

Just for clarification, the function getUrlParameters will return undefined for any param not found, discard it based on typeof undefined and then reconstruct url with your new values

只是为了澄清,函数getUrlParameters将为未找到的任何参数返回undefined,根据typeof undefined丢弃它,然后使用新值重新构建url

#4


1  

Instead of substr, split the params apart and work with them. Here's verbose example to help.

而不是substr,将params分开并与它们一起工作。这是一个冗长的例子来帮助。

var url = 'http://www.domain.com/page/other.jsf?fruit=apple&tree=pine&rock=sedimentary';

/**
* Gets params from url as an object
* @param {String} url
* @return {Object}
*/
var getParams = function (url) {
    var params = {};
    var match = url.match(/\?(.*)$/);

    if (match && match[1]) {
        match[1].split('&').forEach(function (pair) {
            pair = pair.split('=');
            params[pair[0]] = pair[1];
        });
    }

    return params;
};

/**
* Converts an object of params into a query string.
* @param {Object} params
* @return {String}
*/
var paramsToString = function (params) {
    return Object.keys(params || {}).map(function (key) {
        return key + '=' + params[key];
    }).join('&');
};

/**
* Replaces url params.
* @param {String} url
* @param {Object} newParams
* @return {String}
*/
var changeParams = function (url, newParams) {
    var params = getParams(url);

    Object.assign(params, newParams);
    return url.replace(/\?(.*)$/, function () {
        return '?' + paramsToString(params);
    });
};

var urlWithNewParams = changeParams(url, {
    fruit: 'banana',
    weasel: 'yes',
});

console.log(urlWithNewParams); // http://www.domain.com/page/other.jsf?fruit=banana&tree=pine&rock=sedimentary&weasel=yes

#1


1  

You could use Attribute Contains Selector [name*="value"] "a[href*=fruit]" to select a elements that contain "fruit" at href attribute, .attr(attributeName, function) , String.prototype.replace() to replace "apple" with "orange"

您可以使用Attribute Contains Selector [name * =“value”]“a [href * = fruit]”来选择在href属性中包含“fruit”的元素,.attr(attributeName,function),String.prototype.replace( )用“橙色”取代“苹果”

$("a[href*=fruit]").attr("href", function(_, href) {
  return href.replace(/apple/, "orange")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<a href="http://www.domain.com/page/other.jsf?fruit=apple&tree=pine&rock=sedimentary">click me</a>

#2


1  

I used this function to do that :

我用这个函数来做到这一点:

function getQueryParameters (str) {
  return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}

var queryParams = getQueryParameters(myUrl);

result :

结果:

{
    "fruit": "apple",
     ...
}

#3


1  

Heres a way I use to extract url parameters!

这是我用来提取url参数的一种方式!

var getUrlParameter = function(sParam,url) {
    var sPageURL = url;
    if(typeof(sPageURL) === 'undefined' || sPageURL == ''){
        sPageURL = decodeURIComponent(window.location.search.substring(1));
    }
    var sURLVariables = sPageURL.split('&'), sParameterName, i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURI(sParameterName[1]);
        }
    }
};

usage

用法

 getUrlParameter('fruit',url_after_question_mark);

Part 2 of your problem! If your parameters are known or atleast a known set you could always reconstruct the url with fresh values.

问题的第2部分!如果您的参数已知或至少是已知集合,则始终可以使用新值重建URL。

e.g. var params = ['fruit','tree','some_other','some_other2'];//superset of all possible parameters.

例如var params = ['fruit','tree','some_other','some_other2']; //所有可能参数的超集。

Now you could loop through this array and call getUrlParameter function with each of the parameter to see if it exists. If it exists reconstruct your url with fresh values.

现在,您可以遍历此数组并使用每个参数调用getUrlParameter函数以查看它是否存在。如果存在,则使用新值重建您的网址。

Just for clarification, the function getUrlParameters will return undefined for any param not found, discard it based on typeof undefined and then reconstruct url with your new values

只是为了澄清,函数getUrlParameters将为未找到的任何参数返回undefined,根据typeof undefined丢弃它,然后使用新值重新构建url

#4


1  

Instead of substr, split the params apart and work with them. Here's verbose example to help.

而不是substr,将params分开并与它们一起工作。这是一个冗长的例子来帮助。

var url = 'http://www.domain.com/page/other.jsf?fruit=apple&tree=pine&rock=sedimentary';

/**
* Gets params from url as an object
* @param {String} url
* @return {Object}
*/
var getParams = function (url) {
    var params = {};
    var match = url.match(/\?(.*)$/);

    if (match && match[1]) {
        match[1].split('&').forEach(function (pair) {
            pair = pair.split('=');
            params[pair[0]] = pair[1];
        });
    }

    return params;
};

/**
* Converts an object of params into a query string.
* @param {Object} params
* @return {String}
*/
var paramsToString = function (params) {
    return Object.keys(params || {}).map(function (key) {
        return key + '=' + params[key];
    }).join('&');
};

/**
* Replaces url params.
* @param {String} url
* @param {Object} newParams
* @return {String}
*/
var changeParams = function (url, newParams) {
    var params = getParams(url);

    Object.assign(params, newParams);
    return url.replace(/\?(.*)$/, function () {
        return '?' + paramsToString(params);
    });
};

var urlWithNewParams = changeParams(url, {
    fruit: 'banana',
    weasel: 'yes',
});

console.log(urlWithNewParams); // http://www.domain.com/page/other.jsf?fruit=banana&tree=pine&rock=sedimentary&weasel=yes