JavaScript: .trim() does not work in Safari

The reason why trim() doesn’t work in Safari is because this function was only added in JavaScript 1.8.1 for Firefox 3.5. As well as trimLeft(), and trimRight(). As you can see in the JavaScript Reference. Safari’s engine known as Apple Safari 4’s Nitro differs from Mozilla’s TraceMonkey implementation.

I’m sure everybody, one day, passed through this problem. And to fix it, you need to develop your own trimming functionality or use a library like jQuery for example.

UPDATE: Newer versions of Safari will do the trim automatically.

jQuery defines a trim function that you can use like this:

    $.trim(" test ")

And here is the implementation of this function (inside jQuery):

    .toString().replace(/^\s+/, "").replace(/\s+$/, "")

So you can use that for Safari, here’s an example of its use:

<script  type="text/javascript">

    alert(" test ".toString().replace(/^\s+/, "").replace(/\s+$/, ""));

    //displays: test


One thought on “JavaScript: .trim() does not work in Safari

  1. I’m no more guaranteed exactly where you’re obtaining your information and
    facts… I want to spend an afternoon finding out much more and also working
    out additional.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s