Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse URL without protocol in Node using constructor

Tags:

node.js

How can I parse successfully www.stackoverflow.com as a URL using the WHATWG URL API in NodeJS?

If I try new URL("www.stackoverflow.com") I get the error error: URL constructor: www.stackoverflow.com is not a valid URL.

Note: url.parse is deprecated

like image 904
Stefan Zhelyazkov Avatar asked Mar 03 '26 04:03

Stefan Zhelyazkov


1 Answers

Simply do this:

const parsedURL = new URL(url.startsWith("http") ? url : `https://${url}`);
like image 163
Amirhossein Avatar answered Mar 05 '26 00:03

Amirhossein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!