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?

6
  • 1
    'www.stackoverflow.com' isn't a URL. Commented Oct 9, 2018 at 17:58
  • it is acceptable value in our backend and so many other systems. please check this: regextester.com/94502 Commented Oct 9, 2018 at 18:01
  • 1
    Why are you calling parseUrl recursively? This is an unending recursion Commented Oct 9, 2018 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. Commented Oct 9, 2018 at 18:05
  • you are right I fixed the name of the alias. still doesn't work Commented Oct 9, 2018 at 18:05

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

4 Comments

@ChrisG I don't see any result there. Try running it in console
@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.
I see. Than use parser.href = '//www.stackoverflow.com';
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.