我正在開發一個解決方案中的一般函數,該解決方案將用/endpoint/123/disable/lorem
代替/endpoint/{item.id}/disable/{item.name}
,其中我傳遞了URL和項目的函數。JS用對象中的鍵替換子字符串
該項目將是一個對象與鑰匙id
和name
。
如何找到結構爲{item.KEY}
的項目並將其替換爲item.KEY
的最佳方法是什麼?
我正在開發一個解決方案中的一般函數,該解決方案將用/endpoint/123/disable/lorem
代替/endpoint/{item.id}/disable/{item.name}
,其中我傳遞了URL和項目的函數。JS用對象中的鍵替換子字符串
該項目將是一個對象與鑰匙id
和name
。
如何找到結構爲{item.KEY}
的項目並將其替換爲item.KEY
的最佳方法是什麼?
解決這個最好的辦法是通過一個函數來處理正則表達式。 我修改了參數,使easier-我敢肯定,你可以根據需要
var url = '/endpoint/{id}/disable/{name}'; //I modified your parameters
var definition = { id: 123, name: 'lorem' };
url = url.replace(/{([^}]*)}/g, function (prop) {
var key = prop.substr(1, prop.length - 2);
if (definition[key])
return encodeURIComponent(definition[key]);
else
throw new Error('missing required property "' + key + '" in property collection');
});
//alert(url);
撥弄你自己改變這種映射:https://jsfiddle.net/wovr4ct5/2/
如果你不想使用eval,可能使用類似this:
var item = {
id: 123,
KEY: "lorem"
};
function pick(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
然後
str.replace(/{.*?}/g, function(match){ // match {...}
var path = match.substring(1,match.length-1); // get rid of brackets.
return pick(scope, path); //get value and replace it in string.
});
這看起來很像** **這種情況下使用'eval'將會非常危險。很可能無論這些琴絃來自哪裏,它們都沒有被消毒。 –
更安全的解決方案是將'path.split('。')[1]'作爲'item'對象的關鍵字。 :)如果你在你的解決方案中避免使用'eval',那麼它會改變投票的結果。 –
@ this-vidor:好的,完成了。 –
當你說「結構」,你的意思是「子串」? –
@ this-vidor對不起,忘了正確的用語 –
[Template literals](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Template_literals) – Andreas