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?
Thanks
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?
Thanks
I haven't found any string functions in jquery but why not just use the Javascript string object?
For example:
var myStr = new String($("#selector").val());
I came across this while doing some Googling: jquery.strings.js. However, it looks like there may be a conflict with another jQuery plugin. User beware.
Alternatively, depending on the situation, you could stick with using .net methods to format your strings. For example, if you are doing an ajax request, you could format the result with your web method before returning to the client-side.
Acorn
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);
}
There is an official option: jQuery.validator.format.
Comes with jQuery validation plug-in 1.6 (at least).
Quite similar to the String.Format found in .NET.
This is a faster (and prototypical) variation of the function that Josh posted:
String.prototype.format = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
Usage:
'{0} {0} {1} {2}'.format(3.14, 'abc', 'foo'); // outputs: 3.14 3.14 abc foo
'Your balance is {0} USD'.format(77.7)