Extensions for strings, repeat, pad - Node.js String

Node.js examples for String:Padding

Description

Extensions for strings, repeat, pad

Demo Code


/**/*  w  w  w.  j  a v a 2  s.c o m*/
 * extensions for strings
 * 
 * @author Markus Sch?tz
 */
/**
 * potree.js 
 * http://potree.org
 *
 * Copyright 2012, Markus Sch?tz
 * Licensed under the GPL Version 2 or later.
 * - http://potree.org/wp/?page_id=7
 * - http://www.gnu.org/licenses/gpl-3.0.html
 *
 */
String.prototype.repeat = function(count) {
  var msg = "";
  for ( var i = 0; i < count; i++) {
    msg += this;
  }

  return msg;
};

/**
 * fills the string with character to the left, until it reaches the desired length. <br>
 * if string.length is already >= length, the unmodified string will be returned.
 * 
 * @param length
 * @param character
 * @returns {String}
 */
String.prototype.leftPad = function(length, character){
  if(character == null){
    character = ' ';
  }
  
  var padded = "";
  var diff = length - this.length;
  if(diff > 0){
    padded = character.repeat(diff) + this;
  }
  
  return padded;
};

/**
 * fills the string with character to the right, until it reaches the desired length. <br>
 * if string.length is already >= length, the unmodified string will be returned.
 * 
 * @param length
 * @param character
 * @returns {String}
 */
String.prototype.rightPad = function(length, character){
  if(character == null){
    character = ' ';
  }
  
  var padded = "";
  var diff = length - this.length;
  if(diff > 0){
    padded = this + character.repeat(diff);
  }
  
  return padded;
};

Related Tutorials