1

String.Format method of C# allows you to keep "Replaces one or more format items in a specified string with the string representation of a specified object."

string text = "select {0},{1},{2} from {3} where {4};"
var result = String.Format(text, "col1","col2","col3","table","col1 > 10");

after this result would look like

select col1,col2, col3 from table where col1 > 10;

I am also utilizing similar function in JavaScript which looks like this.

this.FormatString = function() {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }
    return s;
};

My question is there any way to use logical name as placeholders instead of using replying on numeric placeholders.

So instead of using

string text = "select {0},{1},{2} from {3} where {4};"

I want to use

string text = "select {Column List} from {TableName} where {Where Clause};"

I know using logical names as placeholders is not generic as compared to having numeric placeholder which allows user to pass N numbers of parameters (or create N numbers of placeholders).

I am looking for solution by using JavaScript or any JavaScript based library.

1

1 Answer 1

3

I'm not sure exactly what you're looking for. Maybe something like this?

var text = 'select {ColumnList} from {TableName} where {WhereClause}';
var values = {
    ColumnList:  'col1, col2, col3',
    TableName:   'table',
    WhereClause: 'col1 > 10'
};

var formatted = formatString(text, values);
// formatted now contains 'select col1, col2, col3 from table where col1 > 10'


function formatString (src, obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            var rx = new RegExp('\\{' + key + '\\}', 'gm');
            src = src.replace(rx, obj[key]);
        }
    }
    return src;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.