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.
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.
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.
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.
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.
I would recommend using the excellent URI.js library if you need to do anything more than super simple URL handling.
If your string is called s
then
var id = s.match(/img_id=([^&]+)/)[1]
will give it to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With