Object prototyping and jQuery.each

I’m using a function on strings to capitalise ( or capitalize, depending on where you’re from :wink: ) them. I wanted to create another function that would iterate through objects and capitalise all their direct variables or one variable within each of the objects in the given object. I’m not very good at explaining it, but here’s what I tried:


String.prototype.capitalise = function() {
    return this.replace(/\\w+/g, function(a)
    {
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
Object.prototype.capitalise = function(sub) {
    if (typeof sub == 'string')
    {
        $(this).each( function() {
            //alert(this[sub]);
            if (typeof this[sub] == 'string') {
                this[sub].capitalise();
            }
        });
    }
    else
    {
        $(this).each( function() {
            if (typeof this == 'string') {
                this.capitalise();
            }
        });
    }
    return this;
};

But i’m getting an error message ‘String contains an invalid character" code: "5’.

If someone could point me in the right direction it’d be a great help.

Regards,
Kieran

Also tried cloning the object and editing the clone instead while iterating through the original, just in case you can’t edit an object directly while iterating through it. (Only just started really going in depth into javascript, so not sure about these things…)


Object.prototype.capitalise = function(sub) {
    var obj = jQuery.extend(true, {}, this);

    if (typeof sub == 'string')
    {
        $(this).each( function(i) {
            //alert(this[sub]);
            if (typeof obj[i][sub] == 'string') {
                obj[i][sub].capitalise();
            }
        });
    }
    else
    {
        $(this).each( function(i) {
            if (typeof obj[i] == 'string') {
                obj[i].capitalise();
            }
        });
    }
    return obj;
};

Still no luck.