I was about to create a trim function in javascript, but as i don't want to reinvent the wheel i googled for this method.
I found this link
http://www.somacon.com/p355.php
The Solution it provided is:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
also it says if you don'y wnt to change the prototype of String then use this:
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
I would like to know in what scenario one should not modify the prototype of String or say any object.
The trim
functions are to be standardised in ECMAScript Fifth Edition, as well as already being present in some browsers. So:
Yes, adding them to the prototype is totally appropriate, but
You shouldn't add them to the prototype if they're already there, as you'll just be replacing a fast native-code function with a slow JavaScript one.
It is also typically marginally faster to do trim as two replaces:
// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
String.prototype.trim= function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With