Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

check if is http and change to https in javascript

  1. User

    check if is http and change to https in javascript

  2. Assistant

    You can use JavaScript to check if a URL starts with "http://", and if so, change it to start with "https://" instead. Here's an example code snippet to accomplish this:

    // Function to check and update the URL to use HTTPS
    function checkAndUpdateURL(url) {
      if (url.startsWith("http://")) {
        url = url.replace("http://", "https://");
      }
      return url;
    }
    
    // Example usage
    let url1 = "http://example.com";
    console.log(checkAndUpdateURL(url1)); // Outputs: https://example.com
    
    let url2 = "https://example.com";
    console.log(checkAndUpdateURL(url2)); // Outputs: https://example.com (unchanged since already using HTTPS)
    
    let url3 = "ftp://example.com";
    console.log(checkAndUpdateURL(url3)); // Outputs: ftp://example.com (unchanged since not using HTTP)
    

    This function checkAndUpdateURL() checks if the URL string starts with "http://". If it does, it replaces "http://" with "https://". If the URL does not start with "http://", it returns the original URL unchanged.