Search code examples
javascriptjquerystring.format

Equivalent of String.format in jQuery


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?


Solution

  • The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.

    Here is the format function...

    String.format = 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;
    }
    

    And here are the endsWith and startsWith prototype functions...

    String.prototype.endsWith = function (suffix) {
      return (this.substr(this.length - suffix.length) === suffix);
    }
    
    String.prototype.startsWith = function(prefix) {
      return (this.substr(0, prefix.length) === prefix);
    }