Posted By

virgil on 09/16/11


Tagged


Versions (?)

Trim function (left, right, both)


 / Published in: JavaScript
 

URL: http://www.somacon.com/p355.php

Trim!

  1. String.prototype.trim = function() {
  2. return this.replace(/^\s+|\s+$/g,"");
  3. }
  4. String.prototype.ltrim = function() {
  5. return this.replace(/^\s+/,"");
  6. }
  7. String.prototype.rtrim = function() {
  8. return this.replace(/\s+$/,"");
  9. }
  10.  
  11. // example of using trim, ltrim, and rtrim
  12. var myString = " hello my name is ";
  13. alert("*"+myString.trim()+"*");
  14. alert("*"+myString.ltrim()+"*");
  15. alert("*"+myString.rtrim()+"*");
  16.  
  17.  
  18.  
  19. /* --------------------- OR ---------------------- */
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26. function trim(stringToTrim) {
  27. return stringToTrim.replace(/^\s+|\s+$/g,"");
  28. }
  29. function ltrim(stringToTrim) {
  30. return stringToTrim.replace(/^\s+/,"");
  31. }
  32. function rtrim(stringToTrim) {
  33. return stringToTrim.replace(/\s+$/,"");
  34. }
  35.  
  36. // example of using trim, ltrim, and rtrim
  37. var myString = " hello my name is ";
  38. alert("*"+trim(myString)+"*");
  39. alert("*"+ltrim(myString)+"*");
  40. alert("*"+rtrim(myString)+"*");

Report this snippet  

You need to login to post a comment.