简体   繁体   English

使用正则表达式和javascript将HTTP URL重写为HTTPS

[英]Rewriting HTTP url to HTTPS using regular expression and javascript

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 =  "https://" + ?;

直接替换正则表达式:

url = url.replace(/^http:\/\//i, 'https://');

Cannot it be done by simply replacing the http string? 简单地替换http字符串不能完成吗?

if(url.match('^http://')){
     url = url.replace("http://","https://")
}

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)

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

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