Computes values ​​from parameterized strings in javascript

Say I have a line, for example:

var map = "/directory/:id/thumbnails/:size";

And I want to use this to match with another line (essentially the same thing that Rails uses to determine routes), for example:

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

I would like to “compare” two strings and return a key-value pair or JSON object that represents the parts strthat are displayed in map, which in my example above looks like this:

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

Would this work well for JavaScript Regex? Can anybody help me?

+3
source share
1 answer

It was easier for me to just write code for this than 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/>");
}

= > http://jsfiddle.net/5qFkb/

, - , . , , , - .

, , ; , , .

+2

Source: https://habr.com/ru/post/1788902/


All Articles