Last active
November 26, 2020 13:50
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ordinally_replace_sample() { | |
const content = getContent(); | |
let replaced = content; | |
replaced = replaced.replace(/&/g, "&"); | |
replaced = replaced.replace(/</g, "<"); | |
replaced = replaced.replace(/>/g, ">"); | |
replaced = replaced.replace(/"/g, """); | |
replaced = replaced.replace(/'/g, "'"); | |
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