string-trim.js 1.1 KB

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