使用jQuery中的动态参数和值更改URL的查询参数 [英] Change query parameters of URL using dynamic parameter and value in jQuery

查看:99
本文介绍了使用jQuery中的动态参数和值更改URL的查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论值类型如何,我都需要更改给定URL的查询参数的值.

I need to change the value of query parameters of the given URL irrespective of value type.

我有类似的功能

function urlGenerator (key, value) {
    var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
    // change the value for given key
    return url;
}

查询参数的顺序不固定.它可以是任何顺序.我认为正则表达式可以找到解决方案.

The order of query parameters are not fixed. It may be of any order. I think the solution can be found by Regex.

我需要通用解决方案,而不管上述指定URL的值类型如何.我需要像下面那样调用上述方法,并且必须获取结果URL.

I need generic solution irrespective of the type of value given to above specified URL. I need to call the above method like following and must get the resultant URL.

result = urlGenerator('id', 15);
result = urlGenerator('name', 'yyy');
result = urlGenerator('dob', '2018-10-20');

提前谢谢!

推荐答案

您可以这样做

因此,在temp变量中,我们使用string template为正则表达式构建表达式,而不是使用RegExp将其更改为regex对象,然后使用replace方法将matched value替换为value supplied in function

So here in temp variable we are building a expression for regex using string template and than using RegExp change it to regex object.And then by using replace method we replace the matched value with the value supplied in function.

function urlGenerator (key, value) {
    let temp = '(?<='+`${key}`+'=)[^&]+'
    let reg = new RegExp(temp,'g');
    console.log(reg);
    var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
    // change the value for given key
    return url.replace(reg, value);
}

result = urlGenerator('id', 15);
console.log(result);
result = urlGenerator('name', 'yyy');
console.log(result);
result = urlGenerator('dob', '2018-10-20');
console.log(result);

这篇关于使用jQuery中的动态参数和值更改URL的查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆