拥有在 javascript ("{0} - {1}",'a','b')
中替换 .NET string.Format
等字符串的机制结果“a - b”
。
我正在寻找用 {0}{1} 替换两个字符串之间的所有内容的机制...
示例:
var str = "([OrderDate] >= Func:{TheApplication().GetProfileAttr('TestDate')} ) and [OrderDate] < 1/1/2013 AND [Name] = Func:{TheApplication().GetProfileAttr('Name')}"
stringFormatProducer(str,"Func:{","}");
会给出结果
"([OrderDate] >= {0} ) and [OrderDate] < 1/1/2013 AND [Name] = {1}"
我以可怕的方式完成了这个机制,我将它拆分为 Func:{
然后 }
然后迭代它,我确信有人已经有了更好的解决方案.
最佳答案
var i = 0;
str.replace(/Func:{[^}]+}/g, function(c) {
return '{' + i++ + '}';
});
或更灵活的方式:
var i = 0,
func = 'Func:';
str.replace(new RegExp(func + '{[^}]+}', 'g'), function(c) {
return '{' + i++ + '}';
});
为您提供完整的方法:
String.prototype.createFormattingString = function(prefix, open, close) {
var re = new RegExp(prefix + open + '[^' + close + ']+' + close, 'g'),
i = 0;
return this.replace(re, function(c) {
return '{' + i++ + '}';
});
};
'(VAR > Func:{ some text })'.createFormattingString('Func:', '{', '}');
'(VAR > Func:[ some text ])'.createFormattingString('Func:', '\\[', '\\]');
关于javascript - 将两个字符串之间的所有内容替换为数字 i++ {0},{1},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23627520/