Alex Rivera | Logout

Rewriting HTTP url to HTTPS using regular expression and javascript

Asked 2011-03-30T19:24:28.030
28

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 form the https url using regular expressions and javascript?

url =  "https://" + ?;
Edit
Report

2 Answers

90

Replace directly with a regex :

url = url.replace(/^http:\/\//i, 'https://');
answered 2011-03-30T19:32:51.960
15

Cannot it be done by simply replacing the http string?

if(url.match('^http://')){
     url = url.replace("http://","https://")
}
answered 2011-03-30T19:27:21.577

Your Answer