سؤال

Have mechanism that replaces strings like .NET string.Format in javascript ("{0} - {1}",'a','b') would result "a - b".

I am looking for mechanism that would Replace everything between two strings with {0}{1}...

Example :

var str = "([OrderDate] >= Func:{TheApplication().GetProfileAttr('TestDate')} ) and [OrderDate] < 1/1/2013 AND [Name] = Func:{TheApplication().GetProfileAttr('Name')}"
stringFormatProducer(str,"Func:{","}");

would give result

"([OrderDate] >= {0} ) and [OrderDate] < 1/1/2013 AND [Name] = {1}"

I have this mechanism done in horrid way where I am splitting it on Func:{ then } then iterating over it, I am sure someone already has a better solution.

هل كانت مفيدة؟

المحلول

var i = 0;

str.replace(/Func:{[^}]+}/g, function(c) {
    return '{' + i++ + '}';
});

Or more flexible way:

var i = 0,
    func = 'Func:';

str.replace(new RegExp(func + '{[^}]+}', 'g'), function(c) {
    return '{' + i++ + '}';
});

A complete method for you:

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:', '\\[', '\\]');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top