views:

61

answers:

3

I have an image tag that looks like this:

<img src="http://www.example.com/render/pattern?obj=patterns/pattern_1&amp;color=7F8C6C&amp;obj=patterns/pattern_2&amp;color=C8D9B0&amp;obj=patterns/pattern_3&amp;color=FFFFD1" width="100" height="100" alt="" />

Is it possible for me to use jQuery/Javascript to search the src attribute to find the text "pattern_1&color=" and then retrieve the 6 characters after that? If so, how would I? If not, how else could I retrieve these 3 hex values?

Thanks

A: 

Is this URL an example, or is this exactly how the url arguments would be structured? I ask this because you could parse the query string with a simple function, but that requires that the argument keys to be unique. So, if it looked more like the following:

?obj1=[value1]&color1=456986&obj2=[value2]&color2=828298

Then it would work. Here's a link that has a very simple JS function you could use to retrieve a named variable from the query string:

http://www.idealog.us/2006/06/javascript_to_p.html

Rich
The provided tag is exactly how the url will be structured.
Rick
+1  A: 

Yes - just use a JavaScript regexp to extract exactly that part of the URL:

jQuery("img").each(function(i) {
    m = i.src.match("pattern_1&color=([0-9A-F]{6})"); /* or ([^&]+) if you want to handle named colors */
    if (m) {
        console.log("Found img with color: " + m[1]);
    }
}
Chris Adams
Perfect! Thanks Chris!
Rick
+1  A: 

You need a way to:

  • parse arbitrary query parameters from urls
  • don't discard duplicate keys

First go:

function parseIt(url) {
    var params = {}; 
    url = (url.split('?')[1] || '');
    url.replace(/([^=&]+)=([^&]*)/g, function(m, key, val) { 
        key = decodeURIComponent(key);
        val = decodeURIComponent(val);
        params[key] = params[key] ? params[key].concat(val) : [val]
    });
    return params
}

The regex and string.replace trick is from John Resig, here.

Hooking it up to your images with jQuery is easy:

$('img').each(function() {
    var colors = parseIt(this.src).color;
    alert(colors); // "7F8C6C,C8D9B0,FFFFD1"
})
Roatin Marth