padStart.js 909 B

1234567891011121314151617181920212223242526272829303132
  1. var toValueString = require('./toValueString')
  2. var isUndefined = require('./isUndefined')
  3. var helperStringRepeat = require('./helperStringRepeat')
  4. /**
  5. * 用指定字符从前面开始补全字符串
  6. *
  7. * @param {String} str 字符串
  8. * @param {Number} targetLength 结果长度
  9. * @param {Number} padString 补全字符
  10. * @return {String}
  11. */
  12. function padStart (str, targetLength, padString) {
  13. var rest = toValueString(str)
  14. targetLength = targetLength >> 0
  15. padString = isUndefined(padString) ? ' ' : '' + padString
  16. if (rest.padStart) {
  17. return rest.padStart(targetLength, padString)
  18. }
  19. if (targetLength > rest.length) {
  20. targetLength -= rest.length
  21. if (targetLength > padString.length) {
  22. padString += helperStringRepeat(padString, targetLength / padString.length)
  23. }
  24. return padString.slice(0, targetLength) + rest
  25. }
  26. return rest
  27. }
  28. module.exports = padStart