Parse an URL in JavaScript

2019-01-03 09:15发布

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.

12条回答
劳资没心,怎么记你
2楼-- · 2019-01-03 09:44

Try this:

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]
查看更多
beautiful°
3楼-- · 2019-01-03 09:44

Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-03 09:44

I wrote a javascript url parsing library, URL.js, you can use it for this.

Example:

url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"
查看更多
别忘想泡老子
5楼-- · 2019-01-03 09:47

You can use the jquery plugin http://plugins.jquery.com/url. $.url("?img_id") will return 33

查看更多
▲ chillily
6楼-- · 2019-01-03 09:49

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.

查看更多
地球回转人心会变
7楼-- · 2019-01-03 09:49

got it from google, try to use this method

function getQuerystring2(key, default_) 
{ 
    if (default_==null) 
    { 
        default_=""; 
    } 
    var search = unescape(location.search); 
    if (search == "") 
    { 
        return default_; 
    } 
    search = search.substr(1); 
    var params = search.split("&"); 
    for (var i = 0; i < params.length; i++) 
    { 
        var pairs = params[i].split("="); 
        if(pairs[0] == key) 
        { 
            return pairs[1]; 
        } 
    } 


return default_; 
}
查看更多
登录 后发表回答