JSFiddle - React, Tailwind, and code Playground
JavaScript
function clean (text) {
var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
regexp = RegExp ('\\b(' + Object.keys (dictionary).join ('|') + ')\\b', 'ig');
return text.replace (regexp, function (_, word) {
_ = dictionary[word.toLowerCase ()];
if (/^[A-Z][a-z]/.test (word)) // initial caps
_ = _.slice (0,1).toUpperCase () + _.slice (1);
else if (/^[A-Z][A-Z]/.test (word)) // all caps
_ = _.toUpperCase ();
return _;
});
}
document.write (clean ("It was the Bad that we saw that AWFUL film.<br/>"));
document.write (clean ("Worse weather was predicted.<br/>"));