javascript - 将两个字符串之间的所有内容替换为数字 i++ {0},{1}

标签 javascript jquery formatting

拥有在 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/

相关文章:

javascript - require 函数返回的数据变得未定义(Js、NodeJs、Discord.js)

javascript - 如何阻止 fullcalendar 在轮询时中断拖动和调整大小

php - 从 PHP 脚本更新进度条

jquery - 使用 JQuery 更改元素的顺序

linux - 格式化为 ext 后无法安装可移动驱动器

javascript click事件仅适用于WebGrid MVC中的第一个元素

javascript - 使用转义关闭确认或警告框可防止访问字段(chrome,edge)

javascript - AJAX 仅更新 div 一次

text - 在同一个 Excel 单元格中使用不同的字体?

c# - 为初始加载编译后的 ASP.Net MVC 切换文化