Home > other >  How do I implement a negative look-behind regular expression without using `(?<!)`?
How do I implement a negative look-behind regular expression without using `(?<!)`?

Time:11-18

I know about the negative look behind (?<!) operator, but it appears that the Javascript engine used in Expo/React-Native does not support it. What I want is to implement the following

export function processEmbedded(text: string): string {
  return text.replace(/(?<!!)\[Embedded\]/gm, "![Embedded]");
}

What I did was a bit hacky in that I stripped and re-added.

export function processEmbedded(text: string): string {
  return text
    .replace(/!\[Embedded\]/gm, "[Embedded]")
    .replace(/\[Embedded\]/gm, "![Embedded]");
}

For my cases it does work, but I am pretty sure there's an edge case where it does not.

CodePudding user response:

You may use this work-around solution using a capture group:

export function processEmbedded(text: string): string {
  return text.replace(/(^|[^!])\[Embedded\]/gm, "$1![Embedded]");
}

RegEx Demo

(^|[^!]) matches start of line or a character that is not ! in first capture group. In the replacement we put it back using $1 back-reference.

  • Related