4

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.

4 Answers 4

3

You don't need regex for this you can simply use URL api

let url = "https://img.evbuc.com/moreStuff"

let parsed = new URL(url)

parsed.host = parsed.host.startsWith('www.') ? parsed.host : "www."+ parsed.host

console.log(parsed)

Sign up to request clarification or add additional context in comments.

4 Comments

True. But no IE support (if that matters)
@Codekie we do have polyfills for that URL polyfill
If you want to use polyfills that is.
If I worried about IE support, all I'd do is worry about IE support.
1

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

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

Comments

1

If you want something that will work with any protocol, try this regex:

var url = "https://img.evbuc.com/moreStuff"
var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://www.")
console.log('new URL: ', new_url)

Comments

0

Simple string operations:

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.