Sunday, January 29, 2012

How to extract relative URL from argument values from request string?


I have a request url / string var like http://ip_or_url:4773/image_renderer.service?action=resize&from_format=png&from_url=http://ip_or_url:4773/my_file.user.file&to_format=jpg&w=1920&h=1200 It looks terribly scary. I wonder how to extract from_url=http://195.19.243.13:4773/my_file.user.file argument pair from it and then extract relative file url from that pair value my_file.user.file ?


3 comments:

  1. With pure javascript. It'll return an array of key/value pairs.

    function getUrlParts(url){
    // url contains your data.
    var qs = url.indexOf("?");
    if(qs==-1) return [];
    var fr = url.indexOf("#");
    var q="";
    q = (fr==-1)? url.substr(qs+1) : url.substr(qs+1, fr-qs-1);
    var parts=q.split("&");
    var vars={};
    for(var i=0;i<parts.length; i++){
    var p = parts[i].split("=");
    vars[unescape(p[0])]= p[1] ? unescape(p[1]):"";
    }
    // vars contain all the variables in an array.
    return vars;
    }


    Let me know if any of your test cases fails.

    ReplyDelete
  2. When the url is in the varaible sUrl:

    var sFromUrl = sUrl.match(/from_url=[^&]*/)[0];
    var sBasename = sFromUrl.match(/[^\/]*$/)[0];


    Also see this example.

    ReplyDelete
  3. Use this to get your url variables in JS

    function getUrlVars()
    {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
    }

    return vars;
    }


    and then string.substring(string.search("/")) to get your piece of string

    ReplyDelete