在URL模板中查找和替换占位符的代码,如下所示
网址占位符,如{cookies:partnumber}
输入
var url = 'http://localhost:3000/product/{cookies:partnumber}/user/{users:userId}';
输出
http://localhost:3000/product/100/user/99
Node.js代码
'use strict';
var _ = require('lodash');
var url = 'http://localhost:3000/product/{cookies:partnumber}/user/{users:userId}';
function parameters(){}
parameters.prototype.getCookies = function(key) {
return '100';
};
parameters.prototype.getUsers = function(key) {
return '99';
};
var splitURL = url.split('/');
_.map(splitURL,function(obj, index){
if(obj.match(/{*}/)){
var k = obj.split(':');
var fn = 'get'
.concat(k[0]
.substring(1)
.toString()
.charAt(0)
.toUpperCase()
.concat(k[0]
.slice(2)
)
).trim();
var key = k[1].substring(0,k[1].length-1);
var p = new parameters();
if (fn in p && typeof p[fn] === "function") {
splitURL[index] = p[fn](key);
}
}
});
console.log(splitURL.join('/'));
请建议,如果有任何其他方式来实现相同的并优化代码。