Break a URL into its components

巧了我就是萌 提交于 2019-11-29 01:49:55
Tak

The parseUri function will do everything you need

Edit Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.

<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>

Hope this will help..

In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested

Also you can use parseUri as Tak suggested

There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme

Example:

$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'

Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:

 a = "http://www.domain.com?queryArg1=somequeryargument";
 query = a.substring(a.indexOf('?')+1);

You could then split the query up based on the &'s and again on the = to get at whatever param you need.

Sorry if this ain't very helpful as its a bit of a low tech method :P

EDIT: Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)

//Quick and dirty query Getter object.
function urlQueryGetter(url){
    //array to store params
    var qParam = new Array();
    //function to get param
    this.getParam = function(x){
    return qParam[x];
    }

    //parse url 
    query = url.substring(url.indexOf('?')+1);
    query_items = query.split('&');
    for(i=0; i<query_items.length;i++){
        s = query_items[i].split('=');
        qParam[s[0]] = s[1];
    }

}

//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!