RegEx - Gender Change

His mother raised him.

Why does this work

const findHim = draft.content.match(/\s(him)[\s|.]/)[1];
var reg = new RegExp(findHim, 'g');
draft.content = draft.content.replace(reg, 'her');

His mother raised her.

And this does not work?

const findHim = draft.content.match(/\s(him)[\s|.]/)[1];
draft.content.replace(new RegExp(findHim, 'g'), "her");

The RegExp object is a way to construct regular expressions. Neither of your examples is proper usage, but the first one probably works because the findHim var is a regular expression match result object, and it’s getting coerced to a string (which would == him) in this case.

All you need in this case is:

draft.content = draft.content.replace(/\s(him)[\s|.]/, 'her');

There problem is “\s(him)[\s|.” will match "him " or “him.”

Thus, this sentence “Her mother raised him.” will turn into “Her mother raised him” – period at the end will be gone. I need “$1”, which in this case “him” to be replaced.

I also need the “g” global to be there to replace all instances.

I guess a solution could be to run two separate replacements?

draft.content = draft.content.replace(/ him /g, ' her ');
draft.content = draft.content.replace(/ him./g, ' her.');

My full “gender change” script looks like this:

// do the replacement…
draft.content = draft.content.replace(/Mr./g, 'Ms.');
draft.content = draft.content.replace(/He /g, 'She ');
draft.content = draft.content.replace(/ he /g, ' she ');
draft.content = draft.content.replace(/His /g, 'Her ');
draft.content = draft.content.replace(/ his /g, ' her ');

draft.content = draft.content.replace(/ him /g, ' her ');
draft.content = draft.content.replace(/ him./g, ' her.');

draft.content = draft.content.replace(/himself/g, 'herself');

// Update content
draft.update();

This line:

will incorrectly replace Mrs. with Ms.. because the . in your match pattern will match any character.

As for the pattern in your initial question, why not use word boundary tokens:

/\b(him)\b/

Then you don’t have to worry if him is followed by a period or not.

1 Like

@roosterboy Thank you. This works.

// Gender Change using word boundary tokens
draft.content = draft.content.replace(/Mr.\s/g, 'Ms. ');
draft.content = draft.content.replace(/\bHe\b/g, 'She');
draft.content = draft.content.replace(/\bhe\b/g, 'she');
draft.content = draft.content.replace(/\bHis\b/g, 'Her');
draft.content = draft.content.replace(/\bhis\b/g, 'her');
draft.content = draft.content.replace(/\bhim\b/g, 'her');
draft.content = draft.content.replace(/himself/g, 'herself');

// Update content
draft.update();