Trim String with test case - Node.js String

Node.js examples for String:Case

Description

Trim String with test case

Demo Code


/** @author Steven Levithan, released as public domain. */
String.prototype.trim = function() {
  var str = this.replace(/^\s+/, '');
  for (var i = str.length - 1; i >= 0; i--) {
    if (/\S/.test(str.charAt(i))) {
      str = str.substring(0, i + 1);/*from  w ww  .  j a v  a  2 s .c  o m*/
      break;
    }
  }
  return str;
}
/*t:
  plan(6, "Testing String.prototype.trim.");
  
  var s = "   a bc   ".trim();
  is(s, "a bc", "multiple spaces front and back are trimmed.");

  s = "a bc\n\n".trim();
  is(s, "a bc", "newlines only in back are trimmed.");
  
  s = "\ta bc".trim();
  is(s, "a bc", "tabs only in front are trimmed.");
  
  s = "\n \t".trim();
  is(s, "", "an all-space string is trimmed to empty.");
  
  s = "a b\nc".trim();
  is(s, "a b\nc", "a string with no spaces in front or back is trimmed to itself.");
  
  s = "".trim();
  is(s, "", "an empty string is trimmed to empty.");

*/

Related Tutorials