Organizational Research By

Surprising Reserch Topic

equivalent of string format in jquery


equivalent of string format in jquery  using -'javascript,jquery,string.format'

I'm trying to move some JavaScript code from MicrosoftAjax to JQuery. I use the JavaScript equivalents in MicrosoftAjax of the popular .net methods, e.g. String.format(), String.startsWith(), etc. Are there equivalents to them in jQuery?
    
asked Oct 19, 2015 by okesh.badhiye
0 votes
3 views



Related Hot Questions



Government Jobs Opening

answered Oct 19, 2015 by suyesh.lokhande
0 votes

I couldn't get Josh Stodola's answer to work, but the following worked for me. Note the specification of prototype. (Tested on IE, FF, Chrome, and Safari.):

String.prototype.format = function() {
    var s = this;
    if(t.length - 1 != args.length){
        alert("String.format(): Incorrect number of arguments");
    }
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }
    return s;
}

s really should be a clone of this so as not to be a destructive method, but it's not really necessary.

answered Oct 19, 2015 by okesh.badhiye
0 votes

This violates DRY principle, but it's a concise solution:

var button = '{text}';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
answered Oct 19, 2015 by deepak gupta
0 votes

Expanding on adamJLev's great answer above, here is the TypeScript version:

// Extending String prototype
interface String {
    format(...params: any[]): string;
}

// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
    var s = this,
        i = params.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
    }

    return s;
};
answered Oct 19, 2015 by ukohale
0 votes

I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.

Usage is similar to c# version:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

Also, added support for using names & object properties

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank
answered Oct 19, 2015 by vijaygupta1980

...