我面临的情况是,我需要在 javascript 中重写 url 并将其从 http 协议切换为 https。
我可以将 https 网址与:
if(url.match('^http://')){
但是如何使用正则表达式和 javascript 形成 https url?
url = "https://" + ?;
直接用正则表达式替换:
url = url.replace(/^http:\/\//i, 'https://');
简单替换http字符串不就可以了吗?
if(url.match('^http://')){
url = url.replace("http://","https://")
}
根据您的情况,您可能更喜欢切片:
processed_url = "http" + initial_url.slice(5);
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)
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)
为什么不保持简单呢:
url.replace("http://", "https://");