Parsing url using url-parse

108 Views Asked by At

I am using library to parse urls on my page:

import * as urlParse from 'url-parse';

const parseUrl = url => {
try {
 return urlParse(url);
} catch (e) {
 return null;
 }
};

The issue is when the url 'www.stackoverflow.com' is passed to the function, parseUrl returns http:localhost\www.stackoverflow.com

should I use to obtain the value http://www.stackoverflow.com?

1

There are 1 best solutions below

4
On

You don't really need any external lib for this:

const parser = document.createElement('a');
parser.href = '//www.stackoverflow.com';
console.log(`${parser.protocol}//${parser.hostname}`); // 'https://stackoverflow.com'