JavaScript: implementing the trim(), ltrim() and rtrim() functions

by ian_smithz

HTML

<button id="all">Trim all</button>

<pre>    Trim    </pre>
<pre>  Ltrim</pre>
<pre>Rtrim  </pre>

CSS

pre {
    background: #ccc;
}

JavaScript

String.prototype.trim = function() {
    var trimmed = this.replace(/^\s+|\s+$/g, '');
    return trimmed;
};
String.prototype.ltrim = function() {
    var trimmed = this.replace(/^\s+/g, '');
    return trimmed;
};
String.prototype.rtrim = function() {
    var trimmed = this.replace(/\s+$/g, '');
    return trimmed;
};


document.getElementById('all').onclick = function() {


    var preS = document.getElementsByTagName('pre'),
        len = preS.length,
        i;
    for (i = 0; i < len; i++) {
        var pre = preS[i];
        var text = pre.firstChild.nodeValue;
        switch (i) {
        case 0:
            pre.firstChild.nodeValue = text.trim();
            break;
        case 1:
            pre.firstChild.nodeValue = text.ltrim();
            break;
        case 2:
            pre.firstChild.nodeValue = text.rtrim();
            break;
        default:
            break;
        }
    }

};