【问题标题】:adding https to any URL before opening it via javascript在通过 javascript 打开之前将 https 添加到任何 URL
【发布时间】:2014-09-12 13:03:43
【问题描述】:

我正在构建一个 javascript 小书签,它可以更改 url 的某些部分并可以打开更新的 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/in/products/index.aspx 不正确。我想在www-stg.myweb.com 之前添加https:// 如果我alert 它或console.log() 它,它会显示正确的东西。但是浏览器会在提交后添加http。

如何克服这个问题?

【问题讨论】:

  • 应该是window.location.href = str1;,不是吗?
  • @Regent:对不起,我已经更新了。问题仍然存在 - 它无法识别 https://www-stg.myweb.com:60002 中的冒号,并且以 https//www-stg.myweb.com:60002/in/products/index.aspx 的身份打开
  • 看起来它在 fiddle 中有效。
  • @manoj,这是工作人员,在 mozilla 和 chrome 中都可以,请告诉我您正在使用的浏览器名称和版本。
  • @Regent:是的,它可以在小提琴中使用,尝试将其添加为书签并单击它。它不会工作

标签: javascript jquery regex url bookmarklet


【解决方案1】:

我建议使用 anchor 元素进行此类操作。不需要复杂的表达方式。

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:// 开头,否则将使用当前主机名。

【讨论】:

  • 让浏览器完成工作是最好的方法(你也可以使用new URL),但看起来你不能假设会给出一个协议
  • 这是我用于书签的完整代码 - javascript: var str = document.URL; var pattern2 = new RegExp('www.myweb.com','i'); var str1 = str.replace(pattern2, 'https://www-stg.myweb.com:60002'); window.location.href = (str1);
  • @RienNeVaPlus 协议始终为 https,我需要将其设为书签。
猜你喜欢
  • 2022-01-05
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
  • 2021-09-01
  • 1970-01-01
相关资源
最近更新 更多