FAQ Topic - How do I trim whitespace? (2009-12-10)

A

Asen Bozhilov

Michael said:
        return function(){
            return this.replace(reTrim,"$1");
^^^^
Should be explicit cast `this' value ToString, because in ES5:

The trim function is intentionally generic; it does not require that
its this value be a String object. Therefore, it can be transferred to
other kinds of objects for use as a method.

String.prototype.trim.call([' x', 'x ']).length;
 
G

Garrett Smith

Asen said:
Garrett said:
It seems simpler and easier to see:

if(!String.prototype.trim) { }

Than:

if(typeof String.prototype.trim !== "undefined") { }

The former is shorter and puts the negation first.

In ECMA5 15.5.4.20 String.prototype.trim refer to object which
internal [[Prototype]] refer Function.prototype. Internal have
[[Call]] and [[Construct]] methods.

While it is true that String.prototype.trim is a function, and it is
true that it has Function.prototype in its prototype chain, neither
String.prototype.trim nor Function.prototype implement [[Construct]].

Any of the following list should result in TypeError:-

new "".trim();
new Function.prototype();
new parseInt
new [].slice

Mozilla's results show an aberration.
But if i explicit define trim function and assign to
String.prototype.trim i don't need from all of that test before i call
`trim'. Because of that i will be use:

if (typeof String.prototype.trim !== 'function')
{
String.prototype.trim = function()
{
//do trim
};
}

So in my code i can directly use:

str.trim();

Without feature test every time when i call `trim' method.

Of course the feature test and patch should be done only once.
 
G

Garrett Smith

Asen said:
Michael said:
return function(){
return this.replace(reTrim,"$1");
^^^^
Should be explicit cast `this' value ToString, because in ES5:

The trim function is intentionally generic; it does not require that
its this value be a String object. Therefore, it can be transferred to
other kinds of objects for use as a method.

String.prototype.trim.call([' x', 'x ']).length;

The FAQ should be accordingly changed to:-

if(!String.prototype.trim) {
String.prototype.trim = function() {
// The trim function is intentionally generic (s 15.5.4.20).
return (this+"").replace(/^\s+|\s+$/g, "");
};
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,197
Latest member
ScottChare

Latest Threads

Top