Here are three functions sadly missing from javascript’s core code. They’re simple string trimming functions, mocking the functionality of the PHP functions with the same name: trim, rtrim (right trim) and ltrim (left trim). They’re easy and unobstrusive to include in any script and can really come in handy… I keep forgetting to post the suckers.
Note: be sure to include all three in your code. The trim() function requires the other two to work.
1 2 3 | String.prototype.ltrim = function() { var re = /\s*((\S+\s*)*)/; return this.replace(re, "$1"); } String.prototype.rtrim = function() { var re = /((\s*\S+)*)\s*/; return this.replace(re, "$1"); } String.prototype.trim = function() { return this.rtrim().ltrim(); } |
Example usage:
1 2 3 4 5 6 7 8 9 | var my_string1 = " Condi!"; var my_string2 = "Rummy! "; var my_string3 = " Brownie! "; alert(my_string1.ltrim()); // alerts "Condi!" alert(my_string1.rtrim()); // alerts " Condi!" alert(my_string2.ltrim()); // alerts "Rummy! " alert(my_string2.rtrim()); // alerts "Rummy!" alert(my_string3.trim()); // alerts "Brownie!" |
Recent Comments