Skip to content

Instantly share code, notes, and snippets.

@xtetsuji
Last active November 26, 2020 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xtetsuji/fd6b0348cc0dfa597dd96150de7b4839 to your computer and use it in GitHub Desktop.
Save xtetsuji/fd6b0348cc0dfa597dd96150de7b4839 to your computer and use it in GitHub Desktop.
Sample: convert from plural String#replace'es change to compact one reduce call. This script can be executed by GAS (some syntaxes require V8 engine support).
function ordinally_replace_sample() {
const content = getContent();
let replaced = content;
replaced = replaced.replace(/&/g, "&");
replaced = replaced.replace(/</g, "&lt;");
replaced = replaced.replace(/>/g, "&gt;");
replaced = replaced.replace(/"/g, "&quot;");
replaced = replaced.replace(/'/g, "&apos;");
console.log("ordinally: " + replaced);
}
function reduce_replace_sample() {
const content = getContent();
const replacer = [[/&/g, "amp"], [/</g, "lt"], [/>/g, "gt"], [/"/g, "quot"], [/'/g, "apos"]];
const replaced = replacer.reduce((acc, [re, ent]) => acc.replace(re, `&${ent};`), content);
console.log("reduce: " + replaced);
}
function getContent() {
return `今日は"いい天気"ですね<!>&<どこか>行きたいですね`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment