Copy link to clipboard
Copied
The error message says that trim() is not a function. I am applying this function to a string.
Assuming that by trimming you mean deleting leading and trailing white space:
function trim (str) {
return str.replace(/^\s+/,'').replace(/\s+$/,'');
}
Peter
Copy link to clipboard
Copied
Assuming that by trimming you mean deleting leading and trailing white space:
function trim (str) {
return str.replace(/^\s+/,'').replace(/\s+$/,'');
}
Peter
Copy link to clipboard
Copied
Thank you for saving my day
Copy link to clipboard
Copied
Or if you want to use it in the form 'myString.trim()', define this at the beginning of your script:
String.prototype.trim = function () {
return this.replace(/^\s+/,'').replace(/\s+$/,'');
}
P.
Copy link to clipboard
Copied
Thanks a lot!
Copy link to clipboard
Copied
pkahrel a écrit:
Or if you want to use it in the form 'myString.trim()', define this at the beginning of your script:
String.prototype.trim = function () { return this.replace(/^\s+/,'').replace(/\s+$/,''); }
P.
Hi Peter,
It's generally better to check for the method availability especially for methods that could be possibly added natively in the future
if (Array.prototype.trim==null) Array.prototype.trim=function(){…
Loic
Copy link to clipboard
Copied
It's generally better to check for the method availability especially for methods that could be possibly added natively in the future
Loic, your optimism is admirable!
Copy link to clipboard
Copied
Trim should also take care of new lines, carriage return, tabs, etc:
/**
* Trim spaces, new lines etc
*
* @param {string} str
* @returns {string}
*/
function trim (str) {
return str.replace(/(^[\s\n\r\t\x0B]+)|([\s\n\r\t\x0B]+$)/g, '');
}
Copy link to clipboard
Copied
What's left otherwise
Copy link to clipboard
Copied
So to consolidate advice/suggestions, something like this should be ideal for our goals right?
if (String.prototype.trim == null) String.prototype.trim = function () {return this.replace(/(^[\s\n\r\t\x0B]+)|([\s\n\r\t\x0B]+$)/g, '')};
Loic, I noticed you used Array.prototype instead of String.prototype.
Any particular reason? will giving Array a trim function also give it to String? Is there even a reason for arrays in general to use the trim function?
Copy link to clipboard
Copied
Wow sorry fo rnot responding to this one. I just missed it. In case it's still worth it. There wasn't any consideration about array over string. I think I just bounced on the topic