DEV Community

loading...

String padEnd() method

Henry Arbolaez
I'm a coffee lover, thinker, and a software engineer. I'm passionate about the idea of bringing people together to collaborate, to build a great product.
・1 min read

String padEnd()

Learn about the padEnd() string method. Which will apply some pads to the current string. The padding will be applied from the end of the string.


/**
 * targetLength => The length of the current string that will include the padding.
 *
 * paddingString` => The string to add to the current string as padding.
 * By default it will be empty string.
 */

str.padEnd(targetLength, paddingString);
Enter fullscreen mode Exit fullscreen mode
const name = 'My name is Henry';

// We want to add to the end of the name three dots ...
// for that we need to get the length of the string plus dynamic and add 3
const nameLen = name.length;
name.padEnd(nameLen + 3, '.');

/**
 * @return "My name is Henry..."
 */
Enter fullscreen mode Exit fullscreen mode

Function to add endPad dynamic:

/**
 * @param {String} string
 * @param {Number} extraPad=0
 * @param {String} delimeter=""
 * @return string
 */

const endPad = (str, extraPad = 0, delimeter = '') => {
  if (!str) return '';

  // get string length dynamic to add end pad
  const strLen = str.length;

  // return padded string with the extra pad and it delimeter
  return str.padEnd(strLen + extraPad, delimeter);
};


// example using endPad():
endPad('123', 3, '.');
/**
 * @return "123..."
 */
Enter fullscreen mode Exit fullscreen mode

Discussion (0)