3 // See http://www.robvanderwoude.com/escapechars.php
4 const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
6 function escapeCommand(arg) {
8 arg = arg.replace(metaCharsRegExp, '^$1');
13 function escapeArgument(arg, doubleEscapeMetaChars) {
17 // Algorithm below is based on https://qntm.org/cmd
19 // Sequence of backslashes followed by a double quote:
20 // double up all the backslashes and escape the double quote
21 arg = arg.replace(/(\\*)"/g, '$1$1\\"');
23 // Sequence of backslashes followed by the end of the string
24 // (which will become a double quote later):
25 // double up all the backslashes
26 arg = arg.replace(/(\\*)$/, '$1$1');
28 // All other backslashes occur literally
30 // Quote the whole thing:
34 arg = arg.replace(metaCharsRegExp, '^$1');
36 // Double escape meta chars if necessary
37 if (doubleEscapeMetaChars) {
38 arg = arg.replace(metaCharsRegExp, '^$1');
44 module.exports.command = escapeCommand;
45 module.exports.argument = escapeArgument;