Question: 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?

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

```
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.

```js
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.

```js
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.