簡體   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