I am trying to replace special characters in a string, with the string being file names as special characters cannot be stored on the Windows filesystem.
What I have tried is simply using replace() on my variable repeatedly until it covers all of the special characters I want to replace. Example code:
//Formats file name to save to Filesystem
function formatFileName(postTitle, postUrl, nsfw) {
return new Promise(resolve => {
//Filter out bad characters
postTitle = postTitle.replace(/\?/g, "[q]");
postTitle = postTitle.replace(/\//g, "[s]");
postTitle = postTitle.replace(/\</g, "[l]");
postTitle = postTitle.replace(/\>/g, "[m]");
postTitle = postTitle.replace(/\"/g, "[quo]");
postTitle = postTitle.replace(/\*/g, "[st]");
While this works, I know that there is definitely a better way out there to do this, and as such, I'd like to find out how I could do so in a cleaner manner.
I've tried refining the code by doing this instead:
let specialCharacters = ["?", "/", "<", ">", "\"", "*", "\\"];
let replacement = ["[q]", "[s]", "[l]", "[m]", "[quo]", "[st]", "[bs]"];
//Replace special characters into filesystem-compatible ones
for (var i = 0; i < specialCharacters.length; i++) {
postTitle.replace(specialCharacters[i], replacement[i]);
}
However, with the newly modified code, it does not replace any of the special characters in the string. I've also tried doing
let specialCharacters = [/\?/g, /\//g, /\</g, /\>/g, /\"/g, /\*/g, /\\/g];
let replacement = ["[q]", "[s]", "[l]", "[m]", "[quo]", "[st]", "[bs]"];
//Replace special characters into filesystem-compatible ones
for (var i = 0; i < specialCharacters.length; i++) {
postTitle.replace(specialCharacters[i], replacement[i]);
}
console.log(postTitle);
resolve(postTitle);
but the outcome did not change. Another thing I tried was to wrap it in an async/await function as I thought that it may be because NodeJS wasn't waiting for the loop to finish, but that did not change anything either.
Could someone please tell me what I'm doing wrong?