简体   繁体   中英

Redirect domain to www Javascript

How i can redirect a domain to www in javascript

http://example.com to http://www.example.com

and this is my code

<script>
if(/http:\/\/?example\.com/.test(document.referrer)) {
   window.location = "http://www.example.com/";
}
</script>

thank you

<script>
if(window.location.hostname === "example.com") {
   window.location.hostname = "www.example.com";
}
</script>

You should use window.location.hostname because document.referrer doesn't always work. If you don't believe me, try it in the inspector of this page. So as you will have something like the one of @Chris :

if(window.location.hostname === "example.com") {
   window.location.hostname = "www.example.com";
}

And avoid regex when it's possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM