Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse an URL in JavaScript

How do I parse an URL with JavaScript (also with jQuery)?

For instance I have this in my string,

url = "http://example.com/form_image_edit.php?img_id=33"

I want to get the value of img_id

I know I can do this easily with PHP with parse_url(), but I want to know how it is possible with JavaScript.

like image 430
Run Avatar asked Jul 11 '11 00:07

Run


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.

How does browser parse URL?

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 parsing of URL?

URL parsing is a function of traffic management and load-balancing products that scan URLs to determine how to forward traffic across different links or into different servers. A URL includes a protocol identifier (http, for Web traffic) and a resource name, such as www.microsoft.com.


2 Answers

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.

like image 151
Sindre Sorhus Avatar answered Oct 13 '22 02:10

Sindre Sorhus


If your string is called s then

var id = s.match(/img_id=([^&]+)/)[1]

will give it to you.

like image 38
Ray Toal Avatar answered Oct 13 '22 01:10

Ray Toal