Change query parameters of URL using dynamic parameter and value in jQuery

删除回忆录丶 提交于 2020-01-06 05:29:05

问题


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

I have a function like,

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.

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');

Thanks in advance!!


回答1:


You can do it like this

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);



回答2:


I use replace to change value by regex.

Try this urlGenerator function :

function urlGenerator(url, field, value) {
    var reg = new RegExp('('+field+'=[^&]*)', "");
    return url.replace(reg, field+'='+value);
}

EDIT:

If you wan't a static url in your function :

function urlGenerator(field, value) {
    var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
    var reg = new RegExp('('+field+'=[^&]*)', "");
    return url.replace(reg, field+'='+value);
}


来源:https://stackoverflow.com/questions/53758183/change-query-parameters-of-url-using-dynamic-parameter-and-value-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!