Skip to content

Instantly share code, notes, and snippets.

@jlong
Created April 20, 2012 13:29
Show Gist options
  • Select an option

  • Save jlong/2428561 to your computer and use it in GitHub Desktop.

Select an option

Save jlong/2428561 to your computer and use it in GitHub Desktop.
URI Parsing with Javascript
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
@icarusysuper

Copy link
Copy Markdown

so great!!

@sloanlance

sloanlance commented Nov 25, 2016

Copy link
Copy Markdown

@HaNdTriX posted the best solution here.

It's better to use new URL(...) when it's available. Only if it's not available (in older browsers, for example) does it make sense to use something else. In that case, the approach @jlong shows here is excellent.

I'm surprised @slevithan hasn't posted his parseUri() function in his gists.

@ybootin

ybootin commented Nov 29, 2016

Copy link
Copy Markdown

take care with this function, because parser.href = null will return the infos relative to the current page

parser.protocol; // => "https:"
parser.hostname; // => "gist.github.com"
parser.port;     // => "80"
parser.pathname; // => "jlong/2428561
...

also parser.href = '/test' will complete protocol, hostname, and others, with the one relative to the current page

@PxyUp

PxyUp commented Dec 22, 2016

Copy link
Copy Markdown

For ftp, ssh, sftp and more i use lib
https://www.npmjs.com/package/uri-parse-lib

@mpjura

mpjura commented Feb 7, 2017

Copy link
Copy Markdown

<3

@artuska

artuska commented Feb 12, 2017

Copy link
Copy Markdown

Well, this great solution works only with 100% consistent URL strings, where all URL parts exists. Try example.com without the protocol:

  1. go to any https:// website, eg. https://microsoft.com
  2. open console
  3. write the code:
var parser = document.createElement('a');
parser.href = "example.com"; // for example, this is user entered URL in some form's input field (`Your home page` field or something) and you trying to parse it with the method above in this topic

(You see the trick? The anchor element you've created is not going to the `example.com`, it is going on the current site's `example.com` section page — `https://microsoft.com/example.com`)
  1. now output the protocol:
console.log(parser.protocol);
  1. it will output https: — because you have created anchor <a> element on https://microsoft.com website
  2. ...
  3. PROFIT

@msteitle

msteitle commented Mar 9, 2017

Copy link
Copy Markdown

<4

@crmsoft

crmsoft commented Mar 29, 2017

Copy link
Copy Markdown

just leave this here

rtmp://rtmp-api.facebook.com:80/rtmp/102083600322?ds=1&s_l=1&a=ATjMssSegtYUsg5du

@AITUncle

Copy link
Copy Markdown

cool !

@mohan-mu

Copy link
Copy Markdown

Why I am getting Port as empty ?
https://jsfiddle.net/mohan_mu/uqf461Lo/

@msaggiorato

Copy link
Copy Markdown

@mohan-mu it's because https default port is 443. Same happens if you use http and port 80.

@jespertheend

jespertheend commented Aug 19, 2017

Copy link
Copy Markdown

Any alternative for doing this from within a service worker?

edit: new URL() seems to do the trick

@bomzj

bomzj commented Sep 7, 2017

Copy link
Copy Markdown

new URL('your_url') is great idea, however it doesn't work in IE https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#Browser_compatibility

@maenotsuzuki

maenotsuzuki commented Dec 5, 2017

Copy link
Copy Markdown

This doesn't work if protocol is " * " .
url=" * ://fgf.com"
" * ://fgf.com"
parser.href = url;
" * ://fgf.com"
parser.protocol
"chrome-extension:" What the hell? It supposed to be "*:" no?

@maxlibin

Copy link
Copy Markdown

praser.href = "google.com"
// relative url + /google.com

probably you want to add this before checking...

if (!/^(?:f|ht)tps?:///.test(url)) {
url = "http://" + url;
}

@WooodHead

Copy link
Copy Markdown

This is helpful. Link anatomy

@seliver

seliver commented Jan 18, 2018

Copy link
Copy Markdown

thanks @HaNdTriX ! Definitely the best solution for chrome.

@solinad21

Copy link
Copy Markdown

hello, if i need slash at end of url?

@FlyingPig-99

FlyingPig-99 commented May 22, 2018

Copy link
Copy Markdown

使用这个可以解决ie10的URL()不存在的问题
use this way to solve problem that ie10 do not have URL() method

@adrianbj

Copy link
Copy Markdown

A bit of a gotcha with Firefox and relative urls. The following works in Chrome and Safari, but not Firefox:

var parser = document.createElement('a');
parser.href = "/pathname/?search=test#hash";
parser.search;

If you need this, then it's best to stick with:

parser.href.split('?')[1];

Of course in this case the ? won't be returned like it is with parser.search

@pulketo

pulketo commented Dec 11, 2018

Copy link
Copy Markdown

like!

@robbie-cahill

Copy link
Copy Markdown

parser.href = window.location

If you want the current page info.

@RobinZhao00

Copy link
Copy Markdown

const parseURL = (url) => {
if (!url) throw new Error('pls input correct url');
url = url.replace(/\s+/g, '');

const parser = document.createElement("a");
parser.href = url;

const queries = parser.search
.replace(/^?/, "")
.split("&")
.map(item => item.split('='))
.reduce((prev, curr) => ({
...prev,
[curr[0]]: curr[1],
}), {});

return {
protocol: parser.protocol,
host: parser.host,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
hash: parser.hash,
queries,
}
};

@tayloraleach

Copy link
Copy Markdown

this is gold

@xx4159

xx4159 commented May 2, 2019

Copy link
Copy Markdown

Thanks for your sharing.
I LOVE this way, but I'm wondering is it better way than regex.

@ZzZombo

ZzZombo commented Jul 8, 2019

Copy link
Copy Markdown

This is not URI parsing, only URL parsing.

@forelabs

Copy link
Copy Markdown

additional you can get the origin at once:

parser.origin // => http://example.com

@frankdors

frankdors commented Oct 18, 2019

Copy link
Copy Markdown

@Connum

Connum commented Feb 28, 2020

Copy link
Copy Markdown

new URL('https://gist.github.com/jlong/2428561?foo=bar#test')

The Best

Note that this will only worl with full absolute URLs and throw an error with for example new URL('options.php'):
TypeError: options.php is not a valid URL.

While the createElement-solution also takes relative URLs (although the result you get back will be a full URL):

let urlParser = document.createElement("a");
urlParser.href = 'options.php';
urlParser.hash = 'foobar';
console.log(urlParser.href);
console.log(urlParser.getAttribute('href'));
// result of both logs is the full URL: https://example.com/options.php#foobar

@martinwojtus

martinwojtus commented May 1, 2020

Copy link
Copy Markdown

parser.host and praser.hostname are available,
parser.host - return domain WITH the port ex: github.com
parser.hostname - return just domain ex: github.com:8080

checked here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment