string-trim.js 1.2 KB

123456789101112131415161718192021222324252627282930
  1. var uncurryThis = require('../internals/function-uncurry-this');
  2. var requireObjectCoercible = require('../internals/require-object-coercible');
  3. var toString = require('../internals/to-string');
  4. var whitespaces = require('../internals/whitespaces');
  5. var replace = uncurryThis(''.replace);
  6. var ltrim = RegExp('^[' + whitespaces + ']+');
  7. var rtrim = RegExp('(^|[^' + whitespaces + '])[' + whitespaces + ']+$');
  8. // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
  9. var createMethod = function (TYPE) {
  10. return function ($this) {
  11. var string = toString(requireObjectCoercible($this));
  12. if (TYPE & 1) string = replace(string, ltrim, '');
  13. if (TYPE & 2) string = replace(string, rtrim, '$1');
  14. return string;
  15. };
  16. };
  17. module.exports = {
  18. // `String.prototype.{ trimLeft, trimStart }` methods
  19. // https://tc39.es/ecma262/#sec-string.prototype.trimstart
  20. start: createMethod(1),
  21. // `String.prototype.{ trimRight, trimEnd }` methods
  22. // https://tc39.es/ecma262/#sec-string.prototype.trimend
  23. end: createMethod(2),
  24. // `String.prototype.trim` method
  25. // https://tc39.es/ecma262/#sec-string.prototype.trim
  26. trim: createMethod(3)
  27. };