Question: I am retrieving some data from an external API using javascript, I'm then displaying this data on a HTML page. 

Within this returned data is a URL, it's in the following format;

```
var url = https://img.evbuc.com/moreStuff

```

I need to rewrite this URL so that it's prefixed with `www`, like this;

```
var url = https://www.img.evbuc.com/moreStuff

```

I want to achieve this using either javascript or jquery.

How can I achieve this? An explanation of the correct code would be great too.

Answer: 
You can use a regular expression to search and replace.

Following example also works with:

* `http://img.evbuc.com/moreStuff`
* `//img.evbuc.com/moreStuff`
* `https://img.evbuc.com/moreStuff//someMoreStuff`

```js
function prependUrl(url) {
  return url.replace(/^([^\/]*)(\/\/)(.*)/, '$1//www.$3');
}

const urls = [
    'https://img.evbuc.com/moreStuff',
    'http://img.evbuc.com/moreStuff',
    '//img.evbuc.com/moreStuff',
    'https://img.evbuc.com/moreStuff//someMoreStuff'
];

urls.forEach((url) => console.log(`${ url } -> ${ prependUrl(url) }`));
```

* The regular expression contains 3 capturing groups:

	1. Select everything up to the first `/` (excluding)
	2. Select the `//` (for protocol root)
	3. Select the rest
* The replacement value takes everything up to the first `/` (which may be an empty string as well)
* Replace the `//` with `//www.`
* Append the rest
Simple string operations:

```js
var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.split('//')[0] + '//www.' + url.split('//')[1]
console.log(newUrl)
```

and yet another way to do this is like this:

```js
var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.replace('https://', 'https://www.')
console.log(newUrl)
```