String functions


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ""); };
  2. String.prototype.ltrim = function(){ return this.replace(/^\s+/, ""); };
  3. String.prototype.rtrim = function(){ return this.replace(/\s+$/, ""); };
  4.  
  5. String.prototype.padLeft = function(str, len, padChar)
  6. {
  7. if(!padChar) padChar = " ";
  8. while(str.length < len){ str = padChar+str; }
  9. return str;
  10. }
  11. String.prototype.padRight = function(str, len, padChar)
  12. {
  13. if(!padChar) padChar = " ";
  14. while(str.length < len){ str = str+padChar; }
  15. return str;
  16. }
  17.  
  18. //opposite of String.slice; removes a section of a string and returns what's left
  19. String.prototype.prune = function(start, end)
  20. {
  21. var result = this.slice(0, start);
  22. if(!isNaN(end)) result += this.slice(end);
  23. return result;
  24. }
  25.  
  26. String.prototype.rot13 = function()
  27. {
  28. var a=97, m=109, n=110, z=122, A=65, M=77, N=78, Z=90;
  29. var len = this.length, c, str = "";
  30. for(var i=0; i<len; i++)
  31. {
  32. c = this.charCodeAt(i);
  33. if((a <= c && c <= m) || (A <= c && c <= M)) str += String.fromCharCode(c+13);
  34. else if((n <= c && c <= z) || (N <= c && c <= Z)) str += String.fromCharCode(c-13);
  35. else str += this[i];
  36. }
  37. return str;
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.