string prototype

Shows how to extend the core functionality in javascript

by mirontoli

HTML

<div id="description">
    This is a little example how to extend the functionality in javascript
</div>
<textarea id="input" cols="40" rows="5" title="skriv"></textarea>
<br/>
<input type="text" id="txt-times" value="5"/>
<input type="button" id="btn-times" value="times"/>

<br/>
<textarea id="output" cols="40" rows="5" title="skriv"></textarea>

CSS

#description {
    margin-bottom:3em;
    font-family: "lucida grande", "tahoma";
    font-size:0.8em;
}

JavaScript

// We extend the string using prototype concept
//An example from 
//http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/
String.prototype.times = function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
}

$("#btn-times").live({
    click: function() {
        var times = $("#txt-times").val() * 1;
        var input = $("#input").val();
        var output = input.times(times);
        $("#output").val(output);
    }
});