ccleve
ccleve

Reputation: 15809

Simplest way to modify a URL in a link?

Our site contains href links to various subdomains: foo.mysite.com, bar.mysite.com. For testing purposes, I'd like to run the site on a completely different main domain name, and point to subdomains off the new domain name.

Rather than manually change all the links, I'd like to have only one version of the site with links that look like this:

<a href="foo.(window.location.hostname)/mypage?myparam=value">Link</a>

What's the simplest syntax for doing this?

I know I could write jQuery code to hijack links, but a simpler in-link syntax would be better.

Upvotes: 0

Views: 154

Answers (4)

Paul Sham
Paul Sham

Reputation: 3205

I've seen back-end systems use an ENV variable to make changes between production environments. For example, you would set an environment variable, like var ENV = 'live' or var ENV = 'production. You could then use that to define what subdomain to use.

var ENV = 'production';

// set subdomain based on ENV variable
var subdomain = 'bar';
if(ENV == 'production'){
   var subdomain = 'foo';
}

// modify every link to use the subdomain
$('a').each(function(){
  var modifyHref = 'http://' + subdomain + $(this).attr('href')
  $(this).attr('href', modifyHref);
});

I don't think you should be doing this on front-end JS though.

If subdomains are an issue, I would set all the paths to <a href="/mypage?myaparam=value">. That way, it won't matter what the subdomain. If you are on the foo subdomain, it will go to "foo.whatever/mypage?myaparam=value", and if you are on the bar subdomain, it will go to "bar.whatever/mypage?myaparam=value".

Upvotes: 0

Moritz Roessler
Moritz Roessler

Reputation: 8651

Couldn't you use javascripts onclick event ? tpo do this :

<a href="#" onclick="javascript:window.location.href = 'foo.' + window.location.hostname + '/mypage?myparam=value';">Link</a>

Upvotes: 0

Trevor
Trevor

Reputation: 9578

You could try on click:

<a href="foo.{host}/mypage?myparam=value"
   onclick="this.href=this.href.replace('{host}', window.location.hostname)">Link</a>

Upvotes: 1

colonelclick
colonelclick

Reputation: 2215

Honestly, the easy way for such a simple, global testing change is to do a search/replace on your whole site. If you want to proceed with your plan, I would use a server side language such as PHP, if possible. It will be much more foolproof for what you want.

Upvotes: 0

Related Questions