繁体   English   中英

用于重定向大多数网址的JavasScript方法:(www。,http://,https://)

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

是否有一个JavaScript方法可以重定向这两个:

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

因为它接缝window.open(url)需要在它前面有http或者它会重定向到mysite.com/wwwgoogle.com

或者我应该使用其他方法重定向?

该解决方案将用于用户输入的URL,因此我需要为尽可能多的输入“样式”提供便利。

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

感谢Rajesh的评论

您甚至可以覆盖window.open()函数,如下所示任何不以httphttps开头的url这个函数都附加http和重定向

请找到以下代码

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");

另一种方法是使用regex

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

样品:

 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')) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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