String repeat in JavaScript, and as a jQuery extension.

| No Comments | No TrackBacks
Repeating a string multiple times isn't as easy as in Perl that you say $str x 3. str * 3 simply gives you a NaN. So I wrote this textbook-code-example-like repeat() funciton, that takes a String and a Number, returns a new String.
function repeat(str, i) {
   if (isNaN(i) || i <= 0) return "";
   return str + repeat(str, i-1);
}

Putting it down as a jquery extension, it becomes this snippet:

(function($){
    $.extend({
        repeat: function(str, i) {
            if (isNaN(i) || i == 0) return "";
            return str + $.repeat(str, i-1);
        }
    })
})(jQuery);

It's used like this:

var rating = 3;
var star = "<img src='star.gif'>";

// Show some number of stars based on rating.
$("#rating").html( $.repeat(star, rating) )

Labels: ,

No TrackBacks

TrackBack URL: http://pub.gugod.org/mt/mt-tb.cgi/60

Leave a comment