使用正则表达式和 javascript 将 HTTP url 重写为 HTTPS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5491196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rewriting HTTP url to HTTPS using regular expression and javascript
提问by stevebot
I'm in a situation where I need to rewrite an url in javascript and switch it from http protocol to https.
我的情况是我需要在 javascript 中重写一个 url 并将其从 http 协议切换到 https。
I can match https urls with:
我可以将 https 网址与:
if(url.match('^http://')){
but how do I form the https url using regular expressions and javascript?
但是如何使用正则表达式和 javascript 形成 https url?
url = "https://" + ?;
回答by Stephan
Replace directly with a regex :
直接用正则表达式替换:
url = url.replace(/^http:\/\//i, 'https://');
回答by MP?kalski
Cannot it be done by simply replacing the httpstring?
不能通过简单地替换http字符串来完成吗?
if(url.match('^http://')){
url = url.replace("http://","https://")
}
回答by Ivan Chaer
Depending on your case, you might prefer to slice:
根据您的情况,您可能更喜欢切片:
processed_url = "http" + initial_url.slice(5);
Example of http to https:
http 到 https 的示例:
var initial_url;
var processed_url;
initial_url = "http://stackoverflow.com/questions/5491196/rewriting-http-url-to-https-using-regular-expression-and-javascript";
processed_url = "https" + initial_url.slice(6);
console.log(processed_url)
Example of https to http:
https 到 http 的示例:
var initial_url;
var processed_url;
initial_url = "https://stackoverflow.com/questions/5491196/rewriting-http-url-to-https-using-regular-expression-and-javascript";
processed_url = "http" + initial_url.slice(5);
console.log(processed_url)