javascriptregex

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

url =  "https://" + ?;

Solution

  • Replace directly with a regex :

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