Skip to content

Instantly share code, notes, and snippets.

@peol
Created November 7, 2010 21:05
Show Gist options
  • Save peol/666828 to your computer and use it in GitHub Desktop.
Save peol/666828 to your computer and use it in GitHub Desktop.
With this short snippet, you can utilize $.format('selector', val1, val2, ...).jQueryMethod1() instead of concating your dynamic strings, making them hard-to-read/debug/whatever
// It works kinda like the asp.net's String.Format, meaning that you use {n} templates,
// {0} = your first argument (after the selector), {1} your second (after the selector) etc.
!function($, undefined) {
$.format = function(selector) {
var sel, args = arguments;
sel = selector.replace(/{\d}/g, function(part) {
var i = parseFloat( part.replace(/{|}/g, '') );
return typeof i === 'number' ? args[i+1] || '' : '';
});
return $(sel);
}
}(jQuery);
// Examples:
// 1. $.format('li[data-id="{0}"] .{1}', 4, 'customClass') -> li[data-id="4"] .customClass
// 2. $.format('li[data-id="{0}"], li[data-subid="{0}"]', 6) -> li[data-id="6"], li[data-subid="6"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment