Wednesday, 29 May 2013

JavaScript - String Extensions #1 [ isEmpty(), left(), right(), contains(), repeat() ]

Often, when I am working with Strings in JavaScript, I need many common functions.
Such as the left(), right(), isEmpty(), contains(), ETC.
To make work easier, I wrote a few to appropriate extensions for String:
  1. /****************************************
  2. * String extensions
  3. ****************************************/
  4. String.prototype.isEmpty = function () {
  5. ///
  6. /// Check if string is empty
  7. ///
  8. return (this.length === 0);
  9. };
  10.  
  11. String.prototype.left = function (subStringLength) {
  12. ///
  13. /// Gets left part of string
  14. ///
  15. if (subStringLength > this.length) return this;
  16. return this.substring(0, subStringLength);
  17. };
  18.  
  19. String.prototype.right = function (subStringLength) {
  20. ///
  21. /// Gets right part of string
  22. ///
  23. if (subStringLength > this.length) return this;
  24. return this.substring(this.length, this.length - subStringLength);
  25. };
  26.  
  27. String.prototype.contains = function (subString) {
  28. ///
  29. /// Checks if strin contains other string
  30. ///
  31. if (this.indexOf(subString) > 0) return true;
  32. return false;
  33. };
  34.  
  35. String.prototype.repeat = function (num) {
  36. ///
  37. /// Repeates string [num]-times
  38. ///
  39. if (isNaN(num)) return null;
  40. if (!(num > 0)) return "";
  41. return new Array(num + 1).join(this);
  42. };

No comments:

Post a Comment

Note: only a member of this blog may post a comment.