Alan
Alan

Reputation: 1287

Replacing letters in specific position in string w/regex(javascript)

I have this regex (regex101).

\b([\w])(\w*?)\1

Substitution: $1$2#

What I need to do is in JavaScript I iterate thru the chosen and guessed words and am currently checking each position for matches. I have a variable i that holds the current position that I would like to substitute the character # for if both letters in the current position match.

Example, If the current words are mummy and the guessed word is mommy after first iteration we would #ummy & #ommy. After checking 3rd position would have #u#my & #o#my. and etc till end would have #u##y & #o##y.

And can I substitute variables into my regex to accommodate different word pairs. So on another iteration if words were apple and maple code would transform two strings to ap#ple & ma#ple. My JavaScript looks like :

      const regex = /\b([\w])(\w*?)\1/gm;
      const subst = `$1$2#`;
      wirdleString = wirdleString.replace(regex, subst);
      guessString = guessString.replace(regex, subst);

I'm sorry my regex skills are very weak. Thanks in advance....

Upvotes: 1

Views: 47

Answers (1)

Sami Hult
Sami Hult

Reputation: 3082

First of all: I don't think this is a task for regexps. The problem is much easier solved using iteration.

That said, as an academic exercise, here's one go to match all characters that differ from "mummy":

(?<=.{0})m(?=.{4})|
(?<=.{1})u(?=.{3})|
(?<=.{2})m(?=.{2})|
(?<=.{3})m(?=.{1})|
(?<=.{3})y(?=.{0})

You can create this by a mapping like this:

const string = "mummy";
const length = string.length;
const exp = string.split('').map((char, index) => 
    `(?<=.{${index}})${char}(?=.{${length - index -1}})`
  ).join('|');

const attempt = "momma";
const result = attempt.replace(new RegExp(exp, 'g'), "#");

// '#o##a'

On a general note, I think an iterative approach would be easier and definitely faster:

const result = [...string].map((char, index) => 
    attempt[index] == char ? '#' : char
  ).join('');

Upvotes: 1

Related Questions