1

If, as here at work, we have test, staging and production environments, such as:

http://test.my-happy-work.com

http://staging.my-happy-work.com

http://www.my-happy-work.com

I am writing some javascript that will redirect the browser to a url such as:

http://[environment].my-happy-work.com/my-happy-video

I need to be able to determine the current environment that we are in.

There is the possibility that I will currently be at a url such as:

http://[environment].my-happy-work.com/my-happy-path/my-happy-resource

I want to be able to grab the window.location but strip it of everything but:

http://[environment].my-happy-work.com

And then append to that string + "/" + "my-happy-video".

I am not skilled with regex, but I suppose there would be a way to parse the window.location up to the ".com"

Thoughts? Thanks!

4 Answers 4

8

Why don't you just use window.location.hostname? That only contains the domain.

You can combine that with window.location.protocol to generate what you need:

var domain = window.location.protocol + "//" + window.location.hostname;

More on window.location.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, then use some regex on the window.location.hostname to determine your subdomain(or environment as you call it), the regex would be something like window.location.hostname.match(/^(.*)\.my-happy-work\.com$/) which will return an array with the captured field(what is enclosed in parenthesis).
3

This expression should do the trick:

^https?://([a-z0-9]+)\.([a-z0-9\-]+)\.[a-z]+

Comments

2

Possibly another option would be to deploy separate code in each environment. Not totally separate code, but maybe set a variable to "PRODUCTION" when in production, or to "STAGING" when in staging mode.

This decouples the mode your application should run in from the domain name.

2 Comments

This is sensible. Don't even need to change the code though - just create an ini/config file on each machine that stores the mode (with a safe fallback if no file found).
(This is assuming you have a server-side script to read such a file and, if necessary, generate the appropriate JS variable.)
0

I wish to point you to: What's a good regular expression to capture the root domain of a given url?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.