Skip to content

Instantly share code, notes, and snippets.

@Nils-van-Kleef
Last active September 12, 2016 13:48
Show Gist options
  • Save Nils-van-Kleef/2b5609ac54d3d32d52c5904ba806a1a7 to your computer and use it in GitHub Desktop.
Save Nils-van-Kleef/2b5609ac54d3d32d52c5904ba806a1a7 to your computer and use it in GitHub Desktop.
Redirect - Replace string. This JavaScript will redirect a visitor to the same URL with a string replaced, preserving the rest of the URL.
/* _optimizely_redirect=http://www.example.com */
var toReplace = "/[TO_REPLACE]";
var newString = "/[NEW_STRING]";
var _optly = {redir: document.createElement("a")};
_optly.redir = {protocol: "https:" == document.location.protocol ? "https://" : "http://",
domain: window.location.hostname,
first: window.location.href.split(toReplace)[0],
second: window.location.href.split(toReplace)[1],
query: window.location.search
};
_optly.redir.href = _optly.redir.first + newString + _optly.redir.second + _optly.redir.query;
window.location.replace(_optly.redir.href);
@allison-rodriguez
Copy link

It looks like you don't need _optly.redir.query since _optly.redir.second already includes the query parameters

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment