0

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?

Afflatus
  • 933
  • 1
  • 12
  • 39
  • 1
    `'www.stackoverflow.com'` isn't a URL. –  Oct 09 '18 at 17:58
  • it is acceptable value in our backend and so many other systems. please check this: https://www.regextester.com/94502 – Afflatus Oct 09 '18 at 18:01
  • 1
    Why are you calling `parseUrl` recursively? This is an unending recursion – dRoyson Oct 09 '18 at 18:03
  • @Afflatus The library doesn't care what's acceptable in your backend or matched by some random pattern somebody posted online. It needs to be a string that doesn't cause an error when you pass it to `URL()`, that's how the library works. –  Oct 09 '18 at 18:05
  • you are right I fixed the name of the alias. still doesn't work – Afflatus Oct 09 '18 at 18:05
  • Unless you specify the protocol i.e. http/https, the parser will consider your first parameter as a relative path. The `baseUrl` parameter defaults to your browser `location` attribute and hence you have the localhost being prefixed. – dRoyson Oct 09 '18 at 18:15

1 Answers1

1

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'
Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27
  • @ChrisG I don't see any result there. Try running it in console – Eugene Tsakh Oct 09 '18 at 18:09
  • 1
    @EugeneTsakh As Chris G states, you've made a relative link, therefore that code will just return the protocol and hostname of whatever page you run it on. If you change your `href` to `www.google.com` and run it in Stack Overflow's console, it will still log `https://stackoverflow.com`. – Tyler Roper Oct 09 '18 at 18:09
  • I see. Than use parser.href = '//www.stackoverflow.com'; – Eugene Tsakh Oct 09 '18 at 18:10
  • @ChrisG Do not edit an answer/code to highlight its shortcomings, as edits should be reserved for positive change and/or clean-up rather than making an answer objectively worse. In this case, a comment is sufficient. – Tyler Roper Oct 09 '18 at 18:11