2014-09-12 68 views
0

我正在構建一個可以更改url的一部分並可以打開更新的URL的javascript書籤。以下是我寫的代碼。在通過javascript打開之前將https添加到任何URL

var str = "www.myweb.com/in/products/index.aspx"; 

var pattern2 = new RegExp('www.myweb.com','i'); 
var str1 = str.replace(pattern2, 'https://www-stg.myweb.com:60002'); 
window.location.href = str1; 

這導致HTTP // www-stg.myweb.com:60002 /英寸/產品/的Index.aspx這在不正確。我想添加https://之前www-stg.myweb.com 如果我alert它或console.log()它,它會顯示正確的東西。但瀏覽器一旦提交,即添加http

如何克服這一點?

+3

它應該是'window.location.href = str1;',不是嗎? – Regent 2014-09-12 13:05:02

+0

@ Regent:對不起,我已更新它。仍然是這個問題 - 它不識別'https://www-stg.myweb.com:60002'中的冒號,並且它打開爲'https // www-stg.myweb.com:60002/in/products/index .aspx' – 2014-09-12 13:10:49

+0

看起來像是在[fiddle]中工作(http://jsfiddle.net/abt9srbm/)。 – Regent 2014-09-12 13:19:03

回答

0

我建議使用錨點這樣的操作元素。不需要複雜的表達式。

var str = '//www.myweb.com/in/products/index.aspx'; 

var a  = document.createElement('a'); 
a.href  = str; 
a.protocol = 'https'; 
a.host  = 'www-stg.myweb.com:60002'; 

console.log('result', a.href); 

Fiddle

確保str開始//http://,否則當前的主機將被使用。

+0

讓瀏覽器做這項工作是最好的方法(你也可以使用'new URL'),但是看起來你不能假定協議會被給出 – 2014-09-12 13:20:36

+0

這裏是我用於書籤的完整代碼 - 'javascript: var str = document.URL; \t \t var pattern2 = new RegExp('www.myweb.com','i'); \t var str1 = str.replace(pattern2,'https://www-stg.myweb.com:60002'); \t window.location.href =(str1); \t' – 2014-09-12 13:37:04

+0

@RienNeVaPlus協議始終是https,我需要將它作爲書籤。 – 2014-09-12 13:45:05