Lodash padEnd When Length Is Shorter Than String

When working with string manipulation in Lodash, developers often need to ensure strings meet a specific minimum length using _.padEnd. This article explains the exact behavior of Lodash’s _.padEnd method when the specified target length is shorter than the source string's actual length, detailing the internal logic, providing code examples, and comparing it to native JavaScript alternatives.

The Short Answer

When the desired length passed to _.padEnd is less than or equal to the length of the target string, Lodash returns the original string completely unchanged. It does not truncate, slice, or throw an error.

Code Example

const _ = require('lodash');

const text = 'JavaScript';

// Target length (5) is shorter than string length (10)
const result = _.padEnd(text, 5);

console.log(result); 
// Output: 'JavaScript'
console.log(result.length); 
// Output: 10

Even if you provide custom padding characters, they are ignored because the condition for adding characters is not met:

const resultWithChars = _.padEnd('Database', 4, '_');

console.log(resultWithChars); 
// Output: 'Database'

How Lodash Handles the Logic Internally

The _.padEnd method operates by calculating how much padding is required to reach the target length:

\[\text{paddingNeeded} = \text{targetLength} - \text{string.length}\]

  1. If paddingNeeded is greater than 0, Lodash creates a padding string using the specified characters (or spaces by default) and appends it to the end of the input.
  2. If paddingNeeded is 0 or a negative number, no padding is generated, and the method directly returns the original string converted to string format.

Because _.padEnd is strictly a padding utility and not a truncation utility, it never shortens strings.

Truncating Strings When Shorter Lengths Are Required

If you require a strict string length where shorter strings are padded and longer strings are trimmed, you must combine _.padEnd with a truncation method.

Using Native JavaScript .slice()

function fitString(str, length, padChar = ' ') {
  return str.length > length 
    ? str.slice(0, length) 
    : str.padEnd(length, padChar);
}

console.log(fitString('Supercalifragilistic', 5)); // 'Super'
console.log(fitString('Hi', 5, '!'));              // 'Hi!!!'

Using Lodash _.truncate

const _ = require('lodash');

function formatExact(str, length) {
  if (str.length > length) {
    return _.truncate(str, { length: length, omission: '' });
  }
  return _.padEnd(str, length);
}

Alignment with Native JavaScript

Lodash's implementation matches the ECMAScript standard for native String.prototype.padEnd(). According to the specification, if targetLength is less than or equal to the string length, the native method also returns the original string without modification.