Skip to content

Instantly share code, notes, and snippets.

@goneri
Created May 13, 2024 20:00
Show Gist options
  • Save goneri/86f5b9f9ef756792a49bab95a5bbde70 to your computer and use it in GitHub Desktop.
Save goneri/86f5b9f9ef756792a49bab95a5bbde70 to your computer and use it in GitHub Desktop.
Take a string with some known city names, remove them from the string, and put them back
const myOriginalContent = 'Montreal (CA: /ˌmʌntriˈɔːl/ ⓘ MUN-tree-AWL; French: Montréal [mɔ̃ʁeal] ⓘ) is the largest city in the province of Quebec, the second-largest in Canada, and the tenth-largest in North America. Founded in 1642 as Ville-Marie, or "City of Mary",[15] it is now named after Mount Royal,[16] the triple-peaked hill around which the early settlement was built.[17] The city is centred on the Island of Montreal[18][19] and a few much smaller peripheral islands, the largest of which is Île Bizard. The city is 196 km (122 mi) east of the national capital, Ottawa, and 258 km (160 mi) southwest of the provincial capital, Quebec City. ';
const re = /(Montr.al|Ottawa|Quebec)/g;
var mapping = new Map<string, string>;
function getAnoValue(secret) {
if (mapping.get(secret) === undefined) {
mapping.set(secret, `city${Math.floor(Math.random() * Math.pow(2, 20))}`);
}
return mapping.get(secret);
}
function getSecretValue(ano) {
let a = mapping.entries().find((entry) => entry[1] === ano);
return a[0]
}
const anonContent = myOriginalContent.replace(re, function(match, g1, g2) {return getAnoValue(g1);});
console.log(anonContent);
console.log("----");
console.log(mapping);
console.log("----");
console.log(anonContent.replace(/(city\d+)/g, function(match, g1, g2) {return getSecretValue(g1);}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment