Search code examples
javascriptjquerygreasemonkey

How do I get URL parameters from a link to form a new link in a Greasemonkey script?


I'm pretty new to jQuery and Greasemonkey, but I want to reform a URL.

For example, given:

http://www.example.com/index.php?value1=blabla1&sid=blabla2&mid=blabla3

I want:

link://www.example.com/blabla1/data/blabla2/blabla3.ext


I tried code like this:

var sid=document.URL.substring(document.URL.indexOf('sid=')+15); 
// How do I set the length of blabla2 ? -7 ?

Hopefully someone understands what I mean and can help me out a little.


Solution

  • Use regular-expression searches to get the values. If you know the param names in advance, it's more straightforward than it looks...

    var searchableStr   = document.URL + '&';
    
    var value1  = searchableStr.match (/[\?\&]value1=([^\&\#]+)[\&\#]/i) [1];
    var sid     = searchableStr.match (/[\?\&]sid=([^\&\#]+)[\&\#]/i)    [1];
    var mid     = searchableStr.match (/[\?\&]mid=([^\&\#]+)[\&\#]/i)    [1];
    

    .
    The last bit is then something like:

    var domain  = searchableStr.match (/\/\/([w\.]*[^\/]+)/i) [1];
    
    var newlink = '//' + domain + '/' + value1 + '/data/' + sid + '/' + mid + '.ext';  
    .
    

     .

    PS: It's only slightly more work if you don't know the names in advance.
    PPS: This is educational code. Beware of extra spaces and malicious data, when using in the wild.