Good post! I think it is important to note that you don't want to overwrite the native function if it exists for the browser that is being used. Also, you want to make sure you remove instances of character 160 (in hex it is A0). Therefore, the following code is probably a better approach at making the trim function available for all browsers:
- Code: Select all
String.prototype.trim = String.prototype.trim || function () {
return this.replace(/^[\u00A0\s]+/, "").replace(/[\s\u00A0]+$/, "");
}
In addition, if you are using a JavaScript that provides the curry function, you may want to check out
this post which shows you how to add trim, trimLeft, and trimRight in four short lines.