Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript url parsing

I have a url like http://mywebsite.com/folder1/folder2/index

How do I parse this above url and get all the values separately? I want the output to be like:

http, mywebsite.com, folder1, folder2, index 
like image 389
Ra. Avatar asked May 05 '10 05:05

Ra.


People also ask

How do you parse a URL?

The url. parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.

What is URL parse ()?

URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

How parse URL in HTML?

Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use it for parsing the given URL. Method 2: In this method we will use URL() to create a new URL object and then use it for parsing the provided URL.

What is URL in JavaScript?

url. A string or any other object with a stringifier — including, for example, an <a> or <area> element — that represents an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base will be ignored. base Optional.


2 Answers

If your URL is held in a variable, you can use the split() method to do the following:

var url = 'http://mywebsite.com/folder1/folder2/index';
var path = url.split('/');

// path[0]     === 'http:';
// path[2]     === 'mywebsite.com';
// path[3]     === 'folder1';
// path[4]     === 'folder2';
// path[5]     === 'index';

If you want to parse the current URL of the document, you can work on window.location:

var path = window.location.pathname.split('/');

// window.location.protocol  === 'http:'
// window.location.host      === 'mywebsite.com'
// path[1]                   === 'folder1';
// path[2]                   === 'folder2';
// path[3]                   === 'index';
like image 55
Daniel Vassallo Avatar answered Oct 01 '22 18:10

Daniel Vassallo


var reader = document.createElement('a');
reader.href = "http://test.example.com:80/pathname/?query=param#hashtag";

Then you can use the following attributes:

reader.protocol
reader.hostname
reader.port
reader.pathname
reader.search
reader.hash
reader.host;

Reference: https://gist.github.com/jlong/2428561

like image 27
meson10 Avatar answered Oct 01 '22 20:10

meson10