escape.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. // See http://www.robvanderwoude.com/escapechars.php
  3. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  4. function escapeCommand(arg) {
  5. // Escape meta chars
  6. arg = arg.replace(metaCharsRegExp, '^$1');
  7. return arg;
  8. }
  9. function escapeArgument(arg, doubleEscapeMetaChars) {
  10. // Convert to string
  11. arg = `${arg}`;
  12. // Algorithm below is based on https://qntm.org/cmd
  13. // Sequence of backslashes followed by a double quote:
  14. // double up all the backslashes and escape the double quote
  15. arg = arg.replace(/(\\*)"/g, '$1$1\\"');
  16. // Sequence of backslashes followed by the end of the string
  17. // (which will become a double quote later):
  18. // double up all the backslashes
  19. arg = arg.replace(/(\\*)$/, '$1$1');
  20. // All other backslashes occur literally
  21. // Quote the whole thing:
  22. arg = `"${arg}"`;
  23. // Escape meta chars
  24. arg = arg.replace(metaCharsRegExp, '^$1');
  25. // Double escape meta chars if necessary
  26. if (doubleEscapeMetaChars) {
  27. arg = arg.replace(metaCharsRegExp, '^$1');
  28. }
  29. return arg;
  30. }
  31. module.exports.command = escapeCommand;
  32. module.exports.argument = escapeArgument;