padStart.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var createPadding = require('./_createPadding'),
  2. stringSize = require('./_stringSize'),
  3. toInteger = require('./toInteger'),
  4. toString = require('./toString');
  5. /**
  6. * Pads `string` on the left side if it's shorter than `length`. Padding
  7. * characters are truncated if they exceed `length`.
  8. *
  9. * @static
  10. * @memberOf _
  11. * @since 4.0.0
  12. * @category String
  13. * @param {string} [string=''] The string to pad.
  14. * @param {number} [length=0] The padding length.
  15. * @param {string} [chars=' '] The string used as padding.
  16. * @returns {string} Returns the padded string.
  17. * @example
  18. *
  19. * _.padStart('abc', 6);
  20. * // => ' abc'
  21. *
  22. * _.padStart('abc', 6, '_-');
  23. * // => '_-_abc'
  24. *
  25. * _.padStart('abc', 3);
  26. * // => 'abc'
  27. */
  28. function padStart(string, length, chars) {
  29. string = toString(string);
  30. length = toInteger(length);
  31. var strLength = length ? stringSize(string) : 0;
  32. return (length && strLength < length)
  33. ? (createPadding(length - strLength, chars) + string)
  34. : string;
  35. }
  36. module.exports = padStart;