views:

178

answers:

2

This works fine in FireFox: $("#listname").val().trim()

But in safari it errors: $("#listname").val().trim() while this does work, $("#listname").val()

Why is that?

+1  A: 

That's because trim is not defined on the String type in all browsers. It is not a jQuery function. You could define the prototype and it should work:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}
Darin Dimitrov
+1 Note that `\s` is buggy in some implementations once you get into non-ASCII whitespace, more here: http://perfectionkills.com/whitespace-deviations/ jQuery's function only handles one of them, but...
T.J. Crowder
+8  A: 

There's no intrinsic trim function on strings. jQuery does define $.trim, but you use it like this:

$.trim($("#listname").val())

E.g., you pass the string into it, rather than calling it from a property on String.

And as the other answerer mentioned, if you like, you can add it to all Strings (although I'd leverage jQuery's function rather than doing my own regexs, because of Unicode vagaries in browsers):

if (!String.prototype.trim) {
    String.prototype.trim = (function() {
        function String_trim() {
            return jQuery.trim(this);
        }
        return String_trim;
    })();
}

I've used a named function there (I always use named functions), but you could use fewer lines of code if you're not bothered:

if (!String.prototype.trim) {
    String.prototype.trim = function() {
        return jQuery.trim(this);
    };
}
T.J. Crowder
Oh I'd be bothered!! Why name something you're never going to refer to again...? (+1 for the prototype sol'n)
Mark
@Mark: For my full rationale, see the link. :-) But basically: Because I want to see useful names in errors, call stacks, lists of breakpoints, etc., etc., etc. While this particular case is pretty simple, it seems like every time I think "Oh, this is too simple to bother with doing that" it comes back and bites me.
T.J. Crowder