javascriptregexstringreplacejsonplaceholder

String manipulation JavaScript - replace placeholders


I have a long string, which I have to manipulate in a specific way. The string can include other substrings which causes problems with my code. For that reason, before doing anything to the string, I replace all the substrings (anything introduced by " and ended with a non escaped ") with placeholders in the format: $0, $1, $2, ..., $n. I know for sure that the main string itself doesn't contain the character $ but one of the substrings (or more) could be for example "$0".

Now the problem: after manipulation/formatting the main string, I need to replace all the placeholders with their actual values again.

Conveniently I have them saved in this format:

// TypeScript
let substrings: { placeholderName: string; value: string }[];

But doing:

// JavaScript
let mainString1 = "main string $0 $1";
let mainString2 = "main string $0 $1";

let substrings = [
  { placeholderName: "$0", value: "test1 $1" },
  { placeholderName: "$1", value: "test2" }
];

for (const substr of substrings) {
  mainString1 = mainString1.replace(substr.placeholderName, substr.value);
  mainString2 = mainString2.replaceAll(substr.placeholderName, substr.value);
}

console.log(mainString1); // expected result: "main string test1 test2 $1"
console.log(mainString2); // expected result: "main string test1 test2 test2"

// wanted result: "main string test1 $1 test2"

is not an option since the substrings could include $x which would replace the wrong thing (by .replace() and by .replaceAll()).

Getting the substrings is archived with an regex, maybe a regex could help here too? Though I have no control about what is saved inside the substrings...


Solution

  • If you're sure that all placeholders will follow the $x format, I'd go with the .replace() method with a callback:

    const result = mainString1.replace(
      /\$\d+/g,
      placeholder => substrings.find(
        substring => substring.placeholderName === placeholder
      )?.value ?? placeholder
    );
    
    // result is "main string test1 $1 test2"