您想从第一个字符串中提取一个键数组并从后者中提取一个值数组,其中值前面是特定模式,后跟特定模式。
没有执行此操作的现有库,但我已经编写了一个实现。您可以在此处找到现场演示。
//## Extension to escape all regex special characters in a string ##
RegExp.quote = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
//## Parsing ##
var parser = PathParser('/{first}/{last}');
var actual = parser('/fred/flintstone');
//## Output ##
var pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(actual, null, " ");
document.body.appendChild(pre);
//## The parser constructor ##
function PathParser(pattern) {
var keys = [];
var keyreg = /\{([a-zA-Z0-9]+)\}/g;
var result;
while ((result = keyreg.exec(pattern)) !== null) {
var pre = "^" + RegExp.quote(pattern.substring(0, result.index)).replace(/\\\{[a-zA-Z0-9]+\\\}/g, ".*");
var post = RegExp.quote(pattern.substring(keyreg.lastIndex)).replace(/\\\{[a-zA-Z0-9]+\\\}/g, ".*") + "$";
keys.push({
pre: pre,
post: post,
text: result[1]
});
}
function parser(valstring) {
var keyarr = keys;
var obj = {};
for (var i = 0; i < keyarr.length; i++) {
var valreg = new RegExp(keyarr[i].pre + "(.*)" + keyarr[i].post);
obj[keyarr[i].text] = valstring.match(valreg)[1];
}
return obj;
}
return parser;
}