Ricardo
Ricardo

Reputation: 8291

trim() : unexpected behavior

As you can see in the picture bellow there is an unexpected behavior of the trim() function, because is stripping the á

enter image description here

This code is part of javascript file that I've included in many projects without problems, but now a client of mine is facing this issue. The sad part is that i haven't access to the source code project client.

Questions

  1. Is it posible to override the implementation of native trim() function in Javascript?
  2. What could the reasons of this behavior?

Upvotes: 3

Views: 531

Answers (1)

Timofey Biryukov
Timofey Biryukov

Reputation: 376

Trying your code in a regular browser show that it works as expected - jsfiddle.

Is it possible to override the implementation of native trim() function in JavaScript?

Yes it is possible but it is considered a bad practice. I'll show how to do that because I think the code has it overridden already. Here is how to do it:

String.prototype.trim = x => console.log('trim override');
'olá'.trim(); // trim override

What could be the reasons for this behavior?

Unless it's run in an unexpected environment it is most likely that the original author has trim overridden to something that is different from native implementation. I would suggest you try to paste the polyfill with original implementation in to the console and checking if running it with that will fix the issue.

Here is the polyfill:

String.prototype.trim = function () {
  return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
console.log('olá'.trim());

If the output of this code gives you the correct result (not trimming á) you found the issue.

Upvotes: 3

Related Questions