B4b4j1
B4b4j1

Reputation: 460

Modify parameter in url (with variables)

So I have the parameter "referer" for the trafic origin :

https://example.com?referer=origin

And the parameter "site" for the site country:

https://example.com?site=us

But on the specific platform I am working with, only the "referer" parameter can be passed through navigation. (this app is remote and I cannot access the sources).

However, I need both parameter to be passed... my idea is to modify the "referer" parameter on the first page view so it becomes :

https://example.com?referer=origin-us

I tried this function :

<script>

function Replace() {
  var paramSite = {{Get Site}};
  var paramRef = {{Get Referer}};
  var url = window.location.toString();
  var newUrl = url.replace(/referer={{Get Referer}}/,  "referer={{Get Referer}}-{{Get Site}}");
  return newUrl.reload
}
<script>

It is working in test variable... but I fail to make it work on the site.

Upvotes: 0

Views: 81

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use this function to get parameter value from url

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

I created a sample code to reach your required.

var paramSite = "https://example.com?site=us"
var paramRef = "https://example.com?referer=origin"

var site = getParameterByName("site", paramSite)

var ref = getParameterByName("referer", paramRef)

var newUrl = updateQueryStringParameter(paramRef, "referer", ref + "-" + site)

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18975

Can you try this method for update query string of url.

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

How can I add or update a query string parameter?

Upvotes: 1

Related Questions