user3658423
user3658423

Reputation: 1944

Regex to ensure HTTPS URL schema

I need to replace 'http://' with 'https://' in a URL (if the former exists); and if 'http://' or 'https://' is not the prefix (schema), then I need to prefix the URL with 'https://'.

I can simply check if the URL begins with 'http' and prefix it to 'https' accordingly or replace 'http' if it exists. It's that simple and takes 2 lines of code, BUT...

Is it possible to do it with one line with a JavaScript regex function?

Upvotes: 0

Views: 211

Answers (3)

J0e3gan
J0e3gan

Reputation: 8938

Regex Solution

Yes, it is possible to do this in one statement using a JS regex replace:

url = url.replace(/^(?:https?:\/\/)?(.*)/, "https://$1");

The snippet below demonstrates the above single-statement, regex solution with http, https, and schemaless URLs.

var schemalessUrl = "www.whatever.com.au";
var httpUrl = "http://www.whatever.com.au";
var httpsUrl = "https://www.whatever.com.au";

var urls = [schemalessUrl, httpUrl, httpsUrl];

for (var i = 0; i < urls.length; i++) {
    urls[i] = urls[i].replace(/^(?:https?:\/\/)?(.*)/, 'https://$1');
    console.log(urls[i]);
    alert(urls[i]);
}

Non-regex Solution

It is also possible to do this in a single statement without a regex replace of course. The ternary conditional operator can collapse just about anything into one statement (for better and worse):

url = url.indexOf('http://') === 0 ? url.replace('http://', 'https://') : (url.indexOf('https://') !== 0 ? 'https://' + url : url);

The snippet below similarly demonstrates the above single-statement, non-regex solution with http, https, and schemaless URLs.

var schemalessUrl = "www.whatever.com.au";
var httpUrl = "http://www.whatever.com.au";
var httpsUrl = "https://www.whatever.com.au";

var urls = [schemalessUrl, httpUrl, httpsUrl];

for (var i = 0; i < urls.length; i++) {
    urls[i] = urls[i].indexOf('http://') === 0 ? urls[i].replace('http://', 'https://') : (urls[i].indexOf('https://') !== 0 ? 'https://' + urls[i] : urls[i]);
    console.log(urls[i]);
    alert(urls[i]);
}

Having said this, I prefer the regex solution, but TMTOWTDI.

Upvotes: 0

Joel Purra
Joel Purra

Reputation: 25117

function simpleHttpsPrefixer(url) {
    return url.replace(/^(?:https?:\/\/)?(.*)/, "https://$1");
}

Upvotes: 1

rurouni88
rurouni88

Reputation: 1173

Just do

var str = "http://www.whatever.com.au";
str = str.replace("http://", "https://");
alert(str);

If you want to one-line it:

url = url.replace("http://", "https://");

Upvotes: 0

Related Questions