I'm in a situation where I need to rewrite an url in javascript and switch it from http protocol to https.
I can match https urls with:
if(url.match('^http://')){开发者_JAVA百科
but how do I form the https url using regular expressions and javascript?
url = "https://" + ?;
Replace directly with a regex :
url = url.replace(/^http:\/\//i, 'https://');
Cannot it be done by simply replacing the http string?
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:
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:
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)
精彩评论