开发者

Parse values out of paramaterized strings in javascript

开发者 https://www.devze.com 2023-02-07 09:27 出处:网络
Say I have a string, such as: var map = \"/directory/:id开发者_如何学运维/thumbnails/:size\"; And I want to use that to map against another string (essentially, the same thing that Rails uses to de

Say I have a string, such as:

var map = "/directory/:id开发者_如何学运维/thumbnails/:size";

And I want to use that to map against another string (essentially, the same thing that Rails uses to define Routes), such as:

var str = "/directory/10/thumbnails/large";

I would like to "compare" the two strings, and return a Key-Value Pair or JSON Object that represents the parts of str that map to map, which in my example above, would look like:

obj = {
    'id'   : '10',
    'size' : 'large'
}

Would this be a good fit for JavaScript Regex? Can anyone help me?


I found it easier to just write the code for this than to explain :)

var map = "/directory/:id/thumbnails/:size";
var str = "/directory/10/thumbnails/large";

var obj = {};

var mapArr = map.split('/');
var strArr = str.split('/');

if (mapArr.length != strArr.length) return false;

for (var i = 0; i < mapArr.length; i++)
{
    var m = mapArr[i];
    var s = strArr[i];

    if (m.indexOf(":") != 0) continue;

    m = m.substring(1);    
    obj[m] = s;
    document.write(m + " = ");
    document.write(obj[m]);
    document.write("<br/>");
}

You can also see it in action here => http://jsfiddle.net/5qFkb/

Do ask if you have any questions, but the code should be self-explanatory. Also be aware that there is no usual null checking and stuff I'd usually put in - this is just meant as a quick and dirty proof of concept.

Oh and in case it wasn't clear from my answer; no, I wouldn't use regex, because then I'd have two problems instead of one.

0

精彩评论

暂无评论...
验证码 换一张
取 消