Christian
Christian

Reputation: 3972

jQuery and the this object

jQuery is too overpowering :(

String.prototype.trim = function () {
    return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
}

when I try to add the above code, I get "this.replace is not a function".

I realise that jQuery references itself as this, so how are you meant to reference this?

Upvotes: 1

Views: 105

Answers (2)

Christian
Christian

Reputation: 3972

Problem solved:

I forgot to put the semi colon on the end of the function and it was running in to the jQuery function

String.prototype.trim = function () {
    return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
};

(function ($) {
......

Upvotes: 0

Elliot Nelson
Elliot Nelson

Reputation: 11557

The code you've posted defines a "trim" method on a String. That allows you to do this:

"  some random string  ".trim();

Sounds like you've copied and pasted the BODY of that trim function into some other jQuery function, like this:

$('#myfield').change(function () {
  this = this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
});

Try this instead:

$('#myfield').change(function () {
  $(this).val($(this).val().trim());
});

Upvotes: 2

Related Questions