What is a general function for JavaScript trim?
<script language="JavaScript" type="text/javascript">
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
</script>
This function is simply called as follows:
var mystr;
mystr = trim(" hello ");
The regular expression replaces any spaces at the beginning of the string parameter, as well as any spaces at the end of the string parameter.
|
How to implement JavaScript trim by extending the String prototype?JavaScript trim can be implemented by extending the String prototype as follow:
<script language="JavaScript" type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
This JavaScript trim function can then be called as a method of any String type:
var mystr = new String(" ABC "); mystr=mystr.trim();
|
How can the JavaScript trim function be modified if efficiency is an issue?Simply use the following line to implement JavaScript trim:
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
In essence, instead of performing the JavaScript trim in one go, a right trim and a left trim is performed seperately. The speed increase is seen when this JavaScript Trim function is applied to longer strings. The speed increase is largely due to optimizations internally to how regular expressions are handled by JavaScript. |
What browser compatibility issues exist with the above JavaScript trim function?Regular expressions can be used with JavaScript version 1.2 and above. Microsoft Internet Explorer 4 and above, Netscape 4 and above, all versions of Firefox, and most other modern web browsers support JavaScript 1.2. |