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?
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?
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+$/,"");
}
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);
};
}