/ Published in: JavaScript
Trim!
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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+$/,""); } // example of using trim, ltrim, and rtrim var myString = " hello my name is "; alert("*"+myString.trim()+"*"); alert("*"+myString.ltrim()+"*"); alert("*"+myString.rtrim()+"*"); /* --------------------- OR ---------------------- */ function trim(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g,""); } function ltrim(stringToTrim) { return stringToTrim.replace(/^\s+/,""); } function rtrim(stringToTrim) { return stringToTrim.replace(/\s+$/,""); } // example of using trim, ltrim, and rtrim var myString = " hello my name is "; alert("*"+trim(myString)+"*"); alert("*"+ltrim(myString)+"*"); alert("*"+rtrim(myString)+"*");
URL: http://www.somacon.com/p355.php