Parse an Url in JavaScript

How do I parse a URL into hostname and path in javascript?

var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"

How to parse a URL?

Please note that this solution is not the best. I made this just to match the requirements of the OP. I personally would suggest looking into the other answers.

THe following regexp will give you back the domain and the rest. :\/\/(.[^\/]+)(.*):

  1. www.google.com
  2. /goosomething

I suggest you studying the RegExp documentation here: http://www.regular-expressions.info/reference.html

Using your function:

function get_domain_name()
{
aaaa="http://www.somesite.se/blah/sdgsdgsdgs";
//aaaa="http://somesite.se/blah/sese";
var matches = aaaa.match(/:\/\/(?:www\.)?(.[^/]+)(.*)/);
alert(matches[1]);
alert(matches[2]);
}

Parse an URL in JavaScript

You can use a trick of creating an a-element, add the url to it, and then use its Location object.

function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}

parseUrl('http://example.com/form_image_edit.php?img_id=33').search

Which will output: ?img_id=33


You could also use php.js to get the parse_url function in JavaScript.


Update (2012-07-05)

I would recommend using the excellent URI.js library if you need to do anything more than super simple URL handling.

Best way to parse URL in ES6

ES6 is part of the language specification, not any particular framework for JavaScript. Therefore, you're not going to find things like URL.parse() in the language.

The APIs you're looking for are part of the host for your application, such as the browser or Node.js. In browser, there is a URL interface: https://developer.mozilla.org/en-US/docs/Web/API/URL

Parse URL with Javascript

You can use

var pagenum = location.pathname.match(/\/page\/(.*)/)[1];

It will extract anything past '/page/' in your URL;

Parse URL in JavaScript

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

parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"

URI Parsing with Javascript

How to read GET data from a URL using JavaScript?

Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.

The a code below works and is still useful in situations where URLSearchParams is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.


function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;

if (query === url || query === "") return;

for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);

if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}

Use as follows:

var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);

which returns a an object like this:

{
"a" : ["a a"], /* param values are always returned as arrays */
"b b": ["b"], /* param names can have special chars as well */
"c" : ["1", "2"] /* an URL param can occur multiple times! */
"d" : [null] /* parameters without values are set to null */
}

So

parseURLParams("www.mints.com?name=something")

gives

{name: ["something"]}

EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.

Node.js url.parse replacement

You can use the newURL() API. More about this can be found here https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_the_whatwg_url_api

In the given code snippet, it can be used as follows:

const http = require('http'),
fs = require('fs'),
const { url } = require('url');

http.createServer((request, response) => {
let addr = request.url,
q = new url(addr),
filePath = '';
})

parse URL with JavaScript or jQuery

This should work

var url = 'example.com/hello/world/20111020/';
//get rid of the trailing / before doing a simple split on /
var url_parts = url.replace(/\/\s*$/,'').split('/');
//since we do not need example.com
url_parts.shift();

Now url_parts will point to the array ["hello", "world", "20111020"].



Related Topics



Leave a reply



Submit