我目前正在编写一个简单的格式化函数,用于替换字符串中的一些占位符。
var format = function (a, c) {
return a.replace(/{ *([^} ]+) *}/g, function (b, a) {
b = c;
a.replace(/[^.|\[\]]+/g, function (a) {
b = b[a];
});
return b;
});
};
该语法目前使用花括号符号表示
{key}
,现在我尝试修改RegExp
模式,使其能够使用百分号替代%key
。var pattern = /{ *([^} ]+) *}/g;
我试图用百分号%
替换括号{}
,但仍然无法正常工作。
var pattern = /% *([^% ]+) */g;
原始的模式在以下条件下正常工作:
var data = {
obj: {
foo: 'Foo',
bar: 'Bar'
},
arr: ['Foo', 'Bar']
};
var objTest = '{obj.foo}, is not equal to {obj.bar}.'
format(objTest, data) // => 'Foo, is not equal to Bar.'
var arrTest = '{arr[0]}, is not equal to {arr[1]}.'
format(arrTest, data) // => 'Foo, is not equal to Bar.'
如果我们使用我的修改后的模式,似乎在每个占位符替换后最后一个字符会被删除:
'%obj.foo, is not equal to %obj.bar.' // => 'undefined is not equal to Bar'
'%arr[0], is not equal to %arr[1]' // => 'undefined is not equal to Bar'
有没有什么想法可以修改
pattern
,使其能够使用百分比符号%
而不是花括号{}
?
,
应该结束一个标识符。然后你可以用[^%, ]
替换[^% ]
。但这意味着你的替换不能处理obj["a,b"]
。你看,你需要实际解析JavaScript标识符(包括所有可能的嵌套),才能使其正常工作。 - Martin Ender