1'use strict'; 2 3function escapeArgument(arg, quote) { 4 // Convert to string 5 arg = '' + arg; 6 7 // If we are not going to quote the argument, 8 // escape shell metacharacters, including double and single quotes: 9 if (!quote) { 10 arg = arg.replace(/([()%!^<>&|;,"'\s])/g, '^$1'); 11 } else { 12 // Sequence of backslashes followed by a double quote: 13 // double up all the backslashes and escape the double quote 14 arg = arg.replace(/(\\*)"/g, '$1$1\\"'); 15 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 21 // All other backslashes occur literally 22 23 // Quote the whole thing: 24 arg = '"' + arg + '"'; 25 } 26 27 return arg; 28} 29 30module.exports = escapeArgument; 31