If excludes url containing www - javascript

I have the below JavaScript, and when the url (window.location) does not contain www. the javascript IS executed
var windowloc = window.location; // http://mywebsite.com/
var homeurl = "http://mywebsite.com/";
if(windowloc==homeurl){
//JavaScript IS EXECUTED
}
and if it does the javascript is not executed.
var windowloc = window.location; // http://www.mywebsite.com/
var homeurl = "http://mywebsite.com/";
if(windowloc==homeurl){
//JavaScript is NOT executed.
}
How can I overcome this by allowing the JavaScript to accept urls (window.location) with and without www.

Use code like this see if the domain has www.mywebsite.com in it:
if (window.location.href.indexOf("//www.mywebsite.com/") != -1) {
// code to execute if it is www.mywebsite.com
} else {
// code to execute if it is not www.mywebsite.com
}
or, you could use just the hostname part of window.location like this to just check for the "www.":
if (window.location.hostname.indexOf("www.") != -1) {
// code to execute if it is www. something
} else {
// code to execute if it is not www. something
}
or if you wanted to check for exactly your entire domain, you could do it like this:
if (window.location.hostname === "www.mywebsite.com" {
// code to execute if it is www.mywebsite.com
} else {
// code to execute if it is not www.mywebsite.com
}

You can overcome that using regex, as I am sure other answers will provide. However, it's best practice for search engine optimization (SEO) to force your http://mywebsite.com/ to do a perminant redirect to http://www.mywebsite.com/ because search engines like Google consider the www. and www-less versions two separate websites.
Then you will not need two separate conditions because your url will always be the www. version.

if (window.location.href.indexOf("://www") === -1) {
// "www" excluded
} else {
// other stuff
}
edited the code sample to be more specific

if(window.location.href.indexOf('mywebsite.com')!= -1){
//do stuff
}

Use the hostname property of the location object to determine what address you're being served under:
if (location.hostname==='mywebsite.com')
// do something
location and other address-owning objects like links have properties like hostname, pathname, search and hash to give you the already-parsed pieces of the URL, so you don't have to try to pick apart URL strings yourself. Don't just look for the presence of www. in the location string as it might be somewhere else in the string that isn't the hostname.
But +1 Justin's answer: if you are trying to redirect alternative addresses such as a non-www address to a canonical address, the right way to do that is with an HTTP 301 redirect and not anything to do with JavaScript. This would normally be configured at the server level, eg for Apache you might use a Redirect in your .htaccess.

Related

Pattern matching never terminates

I have this javascript for pattern matching. When I open the HTML file and the scripts run, it never ends. The page loads forever. The logs inside the if and else never print out. I am unable to find the problem.
var link="https://www.google.co.uk/search?source=hp&ei=EUtVWuX5JpGRkwWW_py4Cg&q=testing+for+schools&oq=testing&gs_l=psy-ab.1.1.0i131k1j0l9.7269.8065.0.9955.7.7.0.0.0.0.175.755.4j3.7.0....0...1.1.64.psy-ab..0.7.754...0i3k1.0.TglIEkPkeIU";
var pattern = "(https:\\/\\/)(.*\\.)*(google.co.uk)(\\/.*)*(\\/)*";
if(link.search(pattern) == 0)
{
console.log("inside if");
console.log("Match");
}
else
{
console.log("inside else");
console.log("Not Match");
}
EDIT:
I need a RegEx that represents almost any URL starts with https. The only thing that is variable is the domain name, e.g. google.co.uk. I thought my RegEx was perfect but it could not handle this case.
EDIT2:
The logic for the patter I need is: (any-sub-domain.)*(domain-name)(/something)* (/)*
EDIT3:
Sorry the previous edit corrected now. It was wrong because I did not put it in code.
Instead of using a regex to parse the whole URL, I suggest first using the URL object of JavaScript to extract the relevant parts of the URL. Then you can check attributes of the URL such as hostname and protocol using if:
var link = "https://www.google.co.uk/search?source=hp&ei=EUtVWuX5JpGRkwWW_py4Cg&q=testing+for+schools&oq=testing&gs_l=psy-ab.1.1.0i131k1j0l9.7269.8065.0.9955.7.7.0.0.0.0.175.755.4j3.7.0....0...1.1.64.psy-ab..0.7.754...0i3k1.0.TglIEkPkeIU";
var urlObject = new URL(link);
console.log(urlObject.hostname); // "www.google.co.uk"
console.log(urlObject.protocol); // "https:"
if (urlObject.protocol === "https:") {
if (urlObject.hostname.endsWith('google.co.uk')) {
console.log("this page is on Google UK");
} else {
console.log("this page is on some other HTTPS web site");
}
} else {
console.log("this page is not secured by HTTPS");
}

JS function that runs only on base url

I'm developing a site that is heavily reliant on javascript for browser history manipulation and only uses one actual page file. I want the script to run a function whenever the user hits the base url of the site, but I'm not sure what method is appropriate. Figured I could make a quick comparison of the current window location, but what if the user types in www instead of http://, or none of them. Something tells me this should be really easy.
if (window.location.href == 'http://mysite.com') {
console.log('you hit the base url, yay');
myFunction();
}
It sounds like you want to isolate the path part of the URL.
function isHomePage() {
return window.location.pathname === '/' || window.location.pathname === '';
}
That should cover your bases, even if the URL is something like
https://www2.example.com:443/#hash
window.location.href always includes the protocol, so there's no issue if the user omits that when typing in the URL.
If by base url, you mean there is no path component or hash fragment, you can check for this as follows:
if (window.location.pathname==='/' && window.location.hash==="") {
console.log('you hit the base url, yay');
myFunction();
}
JavaScript can access the current URL in parts. For this URL:
http://mysite.com/example/index.html
window.location.protocol = "http"
window.location.host = "mysite.com"
window.location.pathname = "example/index.html"
Make it sure to use the host property
if (window.location.host === 'mysite.com') {
console.log('you hit the base url, yay');
myFunction();
}

Get The Current Domain Name With Javascript (Not the path, etc.)

I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to detect the actual domain name that the page is loading from so that I know what to change my content to?
I've looked around for stuff like this but most of it doesn't work the way I want it to.
For instance when using
document.write(document.location)
on JSFiddle it returns
http://fiddle.jshell.net/_display/
i.e. the actual path or whatever that is.
How about:
window.location.hostname
The location object actually has a number of attributes referring to different parts of the URL
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
If you are not interested in the host name (for example www.beta.example.com) but in the domain name (for example example.com), this works for valid host names:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
function getDomain(url, subdomain) {
subdomain = subdomain || false;
url = url.replace(/(https?:\/\/)?(www.)?/i, '');
if (!subdomain) {
url = url.split('.');
url = url.slice(url.length - 2).join('.');
}
if (url.indexOf('/') !== -1) {
return url.split('/')[0];
}
return url;
}
Examples
getDomain('http://www.example.com'); // example.com
getDomain('www.example.com'); // example.com
getDomain('http://blog.example.com', true); // blog.example.com
getDomain(location.href); // ..
Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'
If you wish a full domain origin, you can use this:
document.location.origin
And if you wish to get only the domain, use can you just this:
document.location.hostname
But you have other options, take a look at the properties in:
document.location
You can get it from location object in Javascript easily:
For example URL of this page is:
http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc
Then we can get the exact domain with following properties of location object:
location.host = "www.stackoverflow.com"
location.protocol= "http:"
you can make the full domain with:
location.protocol + "//" + location.host
Which in this example returns http://www.stackoverflow.com
I addition of this we can get full URL and also the path with other properties of location object:
location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.
There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:
let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?([a-zA-Z0-9\-_]{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
Since this question asks for domain name, not host name, a correct answer should be
window.location.hostname.split('.').slice(-2).join('.')
This works for host names like www.example.com too.
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
http://jsfiddle.net/5U366/4/
Use
document.write(document.location.hostname)​
window.location has a bunch of properties. See here for a list of them.
I figure it ought to be as simple as this:
url.split("/")[2]
If you want to get domain name in JavaScript, just use the following code:
var domain_name = document.location.hostname;
alert(domain_name);
If you need to web page URL path so you can access web URL path use this example:
var url = document.URL;
alert(url);
What about this function?
window.location.hostname.match(/\w*\.\w*$/gi)[0]
This will match only the domain name regardless if its a subdomain or a main domain
for my case the best match is window.location.origin
Combining a few answers from the above, the following works really well for me for destroying Cookies:
/**
* Utility method to obtain the domain URI:
*/
fetchDomainURI() {
if (window.location.port.length > 0) {
return window.location.hostname;
}
return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
}
Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.
I'm new to JavaScript, but cant you just use: document.domain ?
Example:
<p id="ourdomain"></p>
<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>
Output:
domain.com
or
www.domain.com
Depending on what you use on your website.
Even if the question is about the domain name, the accepted solution includes the subdomain (eg. you get blog.example.com calling location.hostname).
For future reference I suggest a one-liner to extract only the domain (eg. https://blog.example.com/index.html -> example.com) as Micheal.
location.hostname.split('.').filter(( _, i) => i < 2).join('.')
Beware! It can break when the TLD is composed of two parts (eg. .co.uk). If that's your case change 2 with 3 in the code above.
you can use this to do away with the port number.
var hostname = window.location.host;
var urlWithoutPort = `https://${hostname}`;
console.log(urlWithoutPort);
https://publicsuffix.org/list/
(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)
is needed to correctly parse out all domains without suffixes, working with dots as in the answers above will never completely be correct. Feel free to run the above codes samples against the public suffixes dat file to realize this.
You can roll your own code based on this or use a package like https://www.npmjs.com/package/tldts
getDomainWithoutSuffix('google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.google'); // returns `google`
getDomainWithoutSuffix('foo.google.co.uk'); // returns `google`
getDomainWithoutSuffix('t.co'); // returns `t`
getDomainWithoutSuffix('fr.t.co'); // returns `t`
getDomainWithoutSuffix('https://user:password#example.co.uk:8080/some/path?and&query#hash'); // returns `example`

JavaScript issue with matching URL

How can I add something in JavaScript that will check the web site URL of someone on a web site and then redirect to a certain page on the web site, if a match is found? For example...
The string we want to check for, will be mydirectory, so if someone went to example.com/mydirectory/anyfile.php or even example.com/mydirectory/index.php, JavaScript would then redirect their page / url to example.com/index.php because it has mydirectory in the url, otherwise if no match is found, don't redirect, I'm using the code below:
var search2 = 'mydirectory';
var redirect2 = 'http://example.com/index.php'
if (document.URL.substr(search2) !== -1)
document.location = redirect2
The problem with that, is that it always redirects for me even though there is no match found, does anyone know what's going wrong and is there a faster / better way of doing this?
Use String.indexOf() instead:
if (window.location.pathname.indexOf('searchTerm') !== -1) {
// a match was found, redirect to your new url
window.location.href = newUrl;
}
substr is not what you need in this situation, it extracts substrings out of a string. Instead use indexOf:
if(window.location.pathname.indexOf(search2) !== -1) {
window.location = redirect2;
}
If possible it's better to do this redirect on the server side. It will always work, be more search engine friendly and faster. If your users have JavaScript disabled, they won't get redirected.

Re-Direct with document.url.match

My goal is to redirect my website to (/2012/index.php)
ONLY IF the user goes to ( http://www.neonblackmag.com )
ELSE IF
the user goes to ( http://neonblackmag.com.s73231.gridserver.com ) they will not be re-directed... ( this way i can still work on my website and view it from this url ( the temp url )
I have tried the following script and variations, i have been unsuccessful in getting this to work thus far....
<script language="javascript">
if (document.URL.match("http://www.neonblackmag.com/")); {
location.replace("http://www.neonblackmag.com/2012"); }
</script>
This should work:
<script type="text/javascript">
if(location.href.match(/www.neonblackmag.com/)){
location.replace("http://www.neonblackmag.com/2012");
}
</script>
You should use regular expression as an argument of match (if you're not using https you can drop match for http://...
In your solution the semicolon after if should be removed - and I think that's it, mine is using location.href instead of document.URL.
You can also match subfolders using location.href.match(/www.neonblackmag.com\/subfolder/) etc
Cheers
G.
document.url doesn't appear to be settable, afaict. You probably want window.location
<script type="text/javascript">
if (window.location.hostname === "www.neonblackmag.com") {
window.location.pathname = '/2012';
}
</script>
(Don't use language="javascript". It's deprecated.)
Anyone at any time can disable JavaScript and continue viewing your site. There are better ways to do this, mostly on the server side.
To directly answer your questions, this code will do what you want. Here's a fiddle for it.
var the_url = window.location.href;
document.write(the_url);
// This is our pretend URL
// Remove this next line in production
var the_url = 'http://www.neonblackmag.com/';
if (the_url.indexOf('http://www.neonblackmag.com/') !== -1)
window.location.href = 'http://www.neonblackmag.com/2012/index.php';
else
alert('Welcome');
As I said, this can be easily bypassed. It'd be enough to stop a person who can check email and do basic Google searches.
On the server side is where you really have power. In your PHP code you can limit requests to only coming from your IP, or only any other variable factor, and no one can get in. If you don't like the request, send them somewhere else instead of giving them the page.
header('Location: /2012/index.php'); // PHP code for a redirect
There are plenty of other ways to do it, but this is one of the simpler. Others include, redirecting the entire domain, or creating a test sub domain and only allow requests to that.

Categories