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. I can match https urls with: if(url.match('^http://')){ but how do I fo
Solution 1:
Replace directly with a regex :
url = url.replace(/^http:\/\//i, 'https://');
Solution 2:
Cannot it be done by simply replacing the http string?
if(url.match('^http://')){
url = url.replace("http://","https://")
}
Solution 3:
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)
Post a Comment for "Rewriting Http Url To Https Using Regular Expression And Javascript"