-1

I am creating a function that replaces the string with a

~(number)~.

Now let's say I have a string that says This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2

I want to replace all the 2 in a string with ~86~ but when I am doing so the 2 in ~26~ and ~524~ also getting replaced to ~~86~6~ and ```~5~86~4~.

function replaceGameCoordinate() {
  var string = `This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2`
  var replaceArr = ['2'];
  let patt = new RegExp(`${replaceArr[0]}`, 'gm')
  var newString = string.replace(patt, "~86~");
  console.log(newString);
}
replaceGameCoordinate();

The expected output should be :

This is the replacement of ~26~ and ~524~. We still have ~86~ cadets left. Have~86~go for the next mission.~86~
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

0

So you need a different regex rule. You don't want to replace 2. You want to replace 2 when it's not next to another number or ~.

In order to do this, you can use lookaheads and lookbehinds (although lookbehinds are not yet supported by regexes in JS, I believe, but at least with lookaheads) :

const input = "This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2";

const regex = /2(?![\d~])/gm // Means : "2 when it's not followed by a digit \d or a ~"

console.log( input.replace(regex, "~86~" ) )
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63