time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

escape.js (1172B)


      1 'use strict';
      2 
      3 // See http://www.robvanderwoude.com/escapechars.php
      4 const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
      5 
      6 function escapeCommand(arg) {
      7     // Escape meta chars
      8     arg = arg.replace(metaCharsRegExp, '^$1');
      9 
     10     return arg;
     11 }
     12 
     13 function escapeArgument(arg, doubleEscapeMetaChars) {
     14     // Convert to string
     15     arg = `${arg}`;
     16 
     17     // Algorithm below is based on https://qntm.org/cmd
     18 
     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\\"');
     22 
     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');
     27 
     28     // All other backslashes occur literally
     29 
     30     // Quote the whole thing:
     31     arg = `"${arg}"`;
     32 
     33     // Escape meta chars
     34     arg = arg.replace(metaCharsRegExp, '^$1');
     35 
     36     // Double escape meta chars if necessary
     37     if (doubleEscapeMetaChars) {
     38         arg = arg.replace(metaCharsRegExp, '^$1');
     39     }
     40 
     41     return arg;
     42 }
     43 
     44 module.exports.command = escapeCommand;
     45 module.exports.argument = escapeArgument;