/trunk/jsdoc-toolkit/app/frame/String.js

http://jsdoc-toolkit.googlecode.com/ · JavaScript · 93 lines · 27 code · 4 blank · 62 comment · 15 complexity · 01bf03dca27b2e0612cbc6beb2f78c43 MD5 · raw file

  1. /**
  2. @name String
  3. @class Additions to the core string object.
  4. */
  5. /** @author Steven Levithan, released as public domain. */
  6. String.prototype.trim = function() {
  7. var str = this.replace(/^\s+/, '');
  8. for (var i = str.length - 1; i >= 0; i--) {
  9. if (/\S/.test(str.charAt(i))) {
  10. str = str.substring(0, i + 1);
  11. break;
  12. }
  13. }
  14. return str;
  15. }
  16. /*t:
  17. plan(6, "Testing String.prototype.trim.");
  18. var s = " a bc ".trim();
  19. is(s, "a bc", "multiple spaces front and back are trimmed.");
  20. s = "a bc\n\n".trim();
  21. is(s, "a bc", "newlines only in back are trimmed.");
  22. s = "\ta bc".trim();
  23. is(s, "a bc", "tabs only in front are trimmed.");
  24. s = "\n \t".trim();
  25. is(s, "", "an all-space string is trimmed to empty.");
  26. s = "a b\nc".trim();
  27. is(s, "a b\nc", "a string with no spaces in front or back is trimmed to itself.");
  28. s = "".trim();
  29. is(s, "", "an empty string is trimmed to empty.");
  30. */
  31. String.prototype.balance = function(open, close) {
  32. var i = 0;
  33. while (this.charAt(i) != open) {
  34. if (i == this.length) return [-1, -1];
  35. i++;
  36. }
  37. var j = i+1;
  38. var balance = 1;
  39. while (j < this.length) {
  40. if (this.charAt(j) == open) balance++;
  41. if (this.charAt(j) == close) balance--;
  42. if (balance == 0) break;
  43. j++;
  44. if (j == this.length) return [-1, -1];
  45. }
  46. return [i, j];
  47. }
  48. /*t:
  49. plan(16, "Testing String.prototype.balance.");
  50. var s = "{abc}".balance("{","}");
  51. is(s[0], 0, "opener in first is found.");
  52. is(s[1], 4, "closer in last is found.");
  53. s = "ab{c}de".balance("{","}");
  54. is(s[0], 2, "opener in middle is found.");
  55. is(s[1], 4, "closer in middle is found.");
  56. s = "a{b{c}de}f".balance("{","}");
  57. is(s[0], 1, "nested opener is found.");
  58. is(s[1], 8, "nested closer is found.");
  59. s = "{}".balance("{","}");
  60. is(s[0], 0, "opener with no content is found.");
  61. is(s[1], 1, "closer with no content is found.");
  62. s = "".balance("{","}");
  63. is(s[0], -1, "empty string opener is -1.");
  64. is(s[1], -1, "empty string closer is -1.");
  65. s = "{abc".balance("{","}");
  66. is(s[0], -1, "opener with no closer returns -1.");
  67. is(s[1], -1, "no closer returns -1.");
  68. s = "abc".balance("{","}");
  69. is(s[0], -1, "no opener or closer returns -1 for opener.");
  70. is(s[1], -1, "no opener or closer returns -1 for closer.");
  71. s = "a<bc}de".balance("<","}");
  72. is(s[0], 1, "unmatching opener is found.");
  73. is(s[1], 4, "unmatching closer is found.");
  74. */