Sanitize file or folder names to work with a legacy system I'm in the unfortunate position to where I have to create files and folders programmatically that have to work with a legacy system. In this process, the file and folder names have to be heavily sanitized.

The POST requests that create the files and folders are sent from the client in javascript, while the actual creation happens on a server. For this, I wrote a function used to display to users what their input folder or file names will look like and to sanitize their input to work with the legacy system.

I've let this run over quite a few test cases including irregular file names that broke the legacy system prior and it seems to work fine. I'm curious about what could be improved though, especially with respect to readability and extensibility.

/**
 * @description sanitizes a folder or file name to work with #name of legacy system
 * @author me
 * @param {string} object_name
 * @param {string} mode     "file" / "folder"
 */

function sanitizeFolderOrFile(object_name, mode) {

    if (mode !== 'file' &amp;&amp; mode !== 'folder') {
        return false;
    }

    let suffix = '';
    let retvar = '';

    if (mode === 'file') {
        suffix = object_name.split('.').pop();
        retvar = object_name.replace(new RegExp('(\.' + suffix + ')', 'g'), '');
    } else if (mode === 'folder') {
        retvar = object_name;
    }

    // values to replace
    const replace_values = [{
        value: '+\\&amp;',
        replacement: 'u'
    }, {
        value: 'äÄ',
        replacement: 'ae'
    }, {
        value: 'öÖ',
        replacement: 'oe'
    }, {
        value: 'üÜ',
        replacement: 'ue'
    }, {
        value: 'ß',
        replacement: 'ss'
    }, {
        value: ' \\`\\´\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\§\\"\\\'\\!\\=\\-\\.\\,\\;\\:&lt;&gt;\\|\\^\\°\\*\\+\\~\\%',
        replacement: '_'
    }];

    replace_values.forEach(function(element) {
        retvar = retvar.replace(new RegExp('([' + element.value + '])', 'g'), element.replacement);
    });

    retvar = retvar.toLowerCase();

    if (mode === 'file') {
        retvar += '.' + suffix;
    }

    return retvar;
}
I think you need separate some parts of code.


If you use ES5 with Decorators you can todo general determination Errors, and add for instance, function-condition in this Decorator.
You can apply mechanismes Extract Methods, Simplifying Conditional Expressions and Replace Magic Number with Symbolic Constant from sanitizeFolderOrFile.




/* Decorator file */
 function determinationError(condition) {
   return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;
    descriptor.value = function () {
      try {
         condition.apply(this, arguments);
         method.apply(this, arguments);
      }
      catch(e) {
        console.error(e.message);
      }
    };
    return descriptor;
  };
}

//export determinationError;

/*enum MODE file */
 const MODE = {
     FILE: 'file',
     folder: 'folder'
  };

//export MODE;



/*file sanitizeFolderOrFile */


//determinationError = require('determinationError'); // require our decorator file
//MODE = require('MODE'); // require our MODE file

function isFileOrFolderCondition(mode) {
  if (mode !== MODE.FILE &amp;&amp; mode !== MODE.FOLDER) {
    throw new Error('It is not file or folder') ;
  }
}

  const replaceValues = [{
        value: '+\\&amp;',
        replacement: 'u'
    }, {
        value: 'äÄ',
        replacement: 'ae'
    }, {
        value: 'öÖ',
        replacement: 'oe'
    }, {
        value: 'üÜ',
        replacement: 'ue'
    }, {
        value: 'ß',
        replacement: 'ss'
    }, {
        value: ' \\`\\´\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\§\\"\\\'\\!\\=\\-\\.\\,\\;\\:&lt;&gt;\\|\\^\\°\\*\\+\\~\\%',
        replacement: '_'
    }];

function replacerAndToLowerCase(name) {
   replaceValues.forEach(function(element) {
        name = name.replace(new RegExp('([' + element.value + '])', 'g'), element.replacement);
    });

   return name.toLowerCase();
}

function sanitizeFile(fullName) {
   const ext = fullName.split('.').pop();
   let name = fullName.replace(new RegExp('(\.' + ext + ')', 'g'), '');
   name = replacerAndToLowerCase(name);
        
   return `${name}.${ext}`;
}


function sanitizeFolder(fullName) {
   return replacerAndToLowerCase(fullName);
}


//@determinationError(isFileOrFolderCondition)
function sanitize(mode, name) {
   if (mode === MODE.FILE) {
     return sanitizeFile(name);
   }
   
   return sanitizeFolder(name);
}


const fileName = sanitize(MODE.FILE, 'TeSäÄtTE.txt');
console.log('fileName', fileName);

const folderName = sanitize(MODE.FOLDER, 'SuperFolder???????');
console.log('folderName', folderName);






I added comment in Snippet when you can add Decorator and separate on files