I am writing a Javascript function to convert a sentence from first person to second person. My current test function is as follows:
function statementCreator() {
var sentence = "I went to the movies with my friend, Sally. Sally says that I'm her best friend.";
var transforms = {
"I" : "YOU",
"ME" : "YOU",
"MY" : "YOUR",
"AM" : "ARE",
"MINE" : "YOURS",
"I'M" : "YOU'RE"
};
var pattern = `\\b(?:${Object.keys(transforms).join('|')})\\b`;
var re = new RegExp(pattern, "g");
str = sentence.toUpperCase().replace(re, matched => transforms[matched]);
console.log(str);
}
This creates the following regex pattern:
/\b(?:I|ME|MY|AM|MINE|I'M)\b/g
Which produces the following output:
YOU WENT TO THE MOVIES WITH YOUR FRIEND, SALLY. SALLY SAYS THAT YOU'M HER BEST FRIEND.
I'm very new to Javascript and, so, this is most probably a terrible way to do this and, of course this leaves me with the word YOU'M as part of my output as well.
But, ideally, I'd like a solution that could:
- Allow for me to add new entries into the dictionary and they'd be added to the replacements (like was done here with the
${Object.keys(transforms).join('|')}portion) - Obviously, be able to deal with entries such as
I'M.
What would be a good way to do this and, just in case anyone knows of a completely different way I could easily change from first to second person more easily / correctly, I'd LOVE that answer as well!!
Thanks!