I'm trying to build a Javascript program that switches multiple variations of names with each other.
For example, if I had a string:
let string = "This is Donald Trump and I am Donald J. Trump and I have replaced Barack Obama and Obama was before me."
I would want the output to be:
newString = "This is Barack Obama and I am Barack H. Obama and I have replaced Donald Trump and Trump was before me."
My strategy was to use
let arr = string.split(regex)
in such a way that each chunk of text before and after a regex match is its own index, and each regex match is its own index too. For example:
["This is ", "Donald Trump", " and I am ", "Donald J. Trump", " and I have replaced ", "Barack Obama", " and ", "Obama", " was before me."];
Then check each item of the array to see if it needs to be "switched." For example:
for (let i = 0; i < arr.length; i++) {
// if arr[i] == Donald J. Trump, Donald Trump, or Trump, arr[i] = equivalent Obama variation
// else if arr[i] == Barack H. Obama, Barack Obama, or Obama, arr[i] = equivalent Trump variation
// else arr[i] = arr[i]
}
let newString = arr.join(" ");
htmlElement.innerHTML(newString);
Here's my regex
let regex = /\b(Barack\s)?(H\.\s)?Obama|\b(Donald\s)?(J\.\s)?Trump/;
The regex seems to correctly match all variations of the names.
However, when I write
arr = string.split(regex)
my arr looks like this:
["This is ", undefined, undefined, "Donald ", undefined, " and I am ", undefined, undefined, "Donald ", "J. ", " and I have replaced ", undefined, "Barack ", undefined, undefined, " and ", undefined, undefined, undefined, undefined, " was before me."];
Is there a way to split the string by the multiple variations of the delimiter, but also retain the delimiter in its own array item?