Rewriting HTTP url to HTTPS using regular expression and javascript

后端 未结 3 828
生来不讨喜
生来不讨喜 2021-02-04 00:30

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(\'         


        
相关标签:
3条回答
  • 2021-02-04 00:41

    Cannot it be done by simply replacing the http string?

    if(url.match('^http://')){
         url = url.replace("http://","https://")
    }
    
    0 讨论(0)
  • 2021-02-04 00:58

    Replace directly with a regex :

    url = url.replace(/^http:\/\//i, 'https://');
    
    0 讨论(0)
  • 2021-02-04 01:04

    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)
    
    0 讨论(0)
提交回复
热议问题