简体   繁体   中英

JavasScript method to redirect most urls: (www., http://, https://)

Is there a JavaScript method that would redirect both of these:

url = 'www.google.com';
url = 'https://www.google.com';

As it seams window.open(url) requires to have the http in front of it or it would redirect to mysite.com/wwwgoogle.com

Or should I use another method to redirect?

The solution would be used for user inputted urls so I need to facilitate for as much input "styles" as possible.

if (!url.startsWith('http://') && !url.startsWith('https://')) 
  url = window.location.protocol + '//' + url;

Thanks Rajesh for the comment

You can even override window.open() function as below so any url which does not starts with http or https this function append http and redirect

please find below code

window.open = function (open) {
        return function (url, name, features) {
        url = addhttp(url);
        return open.call(window, url, name, features);
    };
}(window.open);

function addhttp(url) {
   if (!/^(f|ht)tps?:\/\//i.test(url)) {
      url = "http://" + url;
   }
   return url;
}

window.open("google.com");
window.open("https://www.google.com");

An alternate approach would be to use regex

/^http(s?):\/\//

Sample:

 function hasProtocol(url) { var regex = /^http(s?):\\/\\//; return regex.test(url) } function appendProtocol(url) { console.log("parsing url: ", url) // Take your site's protocol instead of any default value return window.location.protocol + "//" + url; } function parseURL(url) { return hasProtocol(url) ? url: appendProtocol(url); } console.log(parseURL('www.google.com')) console.log(parseURL('http://www.google.com')) console.log(parseURL('https://www.google.com')) 

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