Skip to content

Instantly share code, notes, and snippets.

@l2dy
Last active March 3, 2020 02:49
Show Gist options
  • Save l2dy/76f721f1122f8ea0cb44bcf17ab030e5 to your computer and use it in GitHub Desktop.
Save l2dy/76f721f1122f8ea0cb44bcf17ab030e5 to your computer and use it in GitHub Desktop.
Replace word with new word of the same length preserving case
#!/usr/bin/env node
const fs = require('fs');
// https://stackoverflow.com/a/17265031
function matchCase(target, pattern) {
var result = '';
for (var i = 0; i < target.length; i++) {
var c = target.charAt(i);
var p = pattern.charAt(i);
if (/[A-Z]/.test(p)) {
result += c.toUpperCase();
} else {
result += c.toLowerCase();
}
}
return result;
}
const pattern = process.argv[2];
const replacement = process.argv[3];
process.argv.slice(4).forEach((file) => {
const src = fs.readFileSync(file, 'utf8');
const output = src.replace(new RegExp(pattern, 'gi'), match => matchCase(replacement, match));
fs.writeFileSync(file, output, 'utf8');
console.log("written %s", file);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment