Dave's Brain

Browse - Programming Tips - Is there an easy and reliable to parse a URL in javaScript?

Date: 2016jul28
Language: javaScript
Credit: cyberpanther on Hacker News

Q.  Is there an easy and reliable to parse a URL in javaScript?

A.  Use an anchor tag:
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"
Don't use a regular expression.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.