Vinoth Kumar
Vinoth Kumar

Reputation: 663

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

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!!

Upvotes: 0

Views: 3234

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

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

Upvotes: 1

Jouby
Jouby

Reputation: 2471

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

Upvotes: 1

Related Questions