我正在尝试查看是否存在可以执行以下操作的东西。我不想重新发明轮子。
我有一个这样的字符串。这是一个文件名。
2014-12-22-thomas-javascript.md
我希望能够为此架构提供一种格式。
{year}-{month}-{day}-{name}-{topic}.{extension}
我想要一个物体作为返回。
{
"year": "2014",
"month": "12",
"day": "22",
"name": "thomas",
"topic": "javascript",
"extension": "md"
}
这种提供字符串和格式的方式对 Node core util、moment parse 和 jekyll post 名称中的这两个函数非常保守。
最佳答案
冒着重新发明轮子的风险;
String.parse = function parse() {
if(typeof arguments[0] === 'string' && typeof arguments[1] === 'string' ) {
var str = arguments[0];
var val = arguments[1];
var array = [], obj = {};
var re = /(?:{)([a-z]*)(?:})/gi;
var match, sre = str;
while(match = re.exec(str)) {
array.push(match[1]);
sre = sre.replace(match[0], '(\\w*)');
}
re = new RegExp(sre);
var matches = val.match(re);
if(matches) {
for(var i = 1; i < matches.length; i++) {
obj[array[i-1]] = matches[i];
}
}
return obj;
}
}
毫无疑问,有很多方法会破坏它,但适用于您的示例;
String.parse("{年}-{月}-{日}-{名称}-{主题}.{扩展名}", "2014-12-22-thomas-javascript.md") ;
编辑
并执行相反的操作;
String.format = function format() {
if (typeof arguments[0] === 'string') {
var s = arguments[0];
var re = /(?:{)(\d*)(?:})/gi;
var a, i, match, search = s;
while (match = re.exec(search)) {
for (i = 1; i < arguments.length; i++) {
a = parseInt(match[1]) + 1;
s = s.replace(match[0], typeof arguments[a] !== 'object' ? arguments[a] || '' : '');
}
}
re = /(?:{)([a-z]*)(?:})/gi;
match, search = s;
while (match = re.exec(search)) {
for (i = 1; i < arguments.length; i++) {
if (arguments[i].hasOwnProperty(match[1])) {
s = s.replace(match[0], arguments[i][match[1]]);
}
}
}
return s;
}
}
它可以接受命名对象成员或非对象的位置。
String.format("{0}-{name}{1}-{year}-{src}", 20, "abc", { name: "xyz", 年份: 2014 }, { src: 'StackOverflow' });
20-xyzabc-2014-StackOverflow
关于javascript - 从格式化字符串中提取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27611398/