Home > Back-end >  How do you replace certain part of the string using regex?
How do you replace certain part of the string using regex?

Time:06-01

I am doing a project on javascript. I am facing some issues with string replacement. The string basically will contain latex. ie.

\frac{2}{3}^{\x=\frac{2}{3}} 

How do i replace only all the instance of \frac that DOES NOT appear in between ^{ } with \dfrac using regex or javascript function?

Edit : A big thanks for all your input. But I have phase my questions wrongly. I need those that are not inside the ^{ .... } to be replaced with dfrac and there might be multiple instances of frac happening.

Example :

\frac{2}{3} \frac{4}{5}^{\frac{7}{8} \frac{8}{9}} \frac{10}{11} 

I will need the output to be

\dfrac{2}{3} \dfrac{4}{5}^{\frac{7}{8} \frac{8}{9}} \dfrac{10}{11} 

CodePudding user response:

I'm sure I'll be flogged for this but I have zero familiarity with LaTeX parsing so from a purely char-based replacement mindset you could do:

regex

(\{[^{}]*?\\)(frac)
  • (\{[^{}]*?\\) - find an open curly brace, followed by an unlimited amount of non curly braces, followed by a backslash, and store it all in capture group #1
  • (frac) - ensure that "frac" follows next and store it in capture group #2

replace

$1d$2
  • Put a d in between {\x=\ and frac

discalimer: there will undoubtedly be edge-cases in which false positives occur and false negatives get missed.

https://regex101.com/r/V03tFs/1

CodePudding user response:

Will this work for you?

const lat = String.raw`\frac{2}{3}^{\x=\frac{2}{3}}`;
const parts = lat.split("frac")
const newLat = parts.map((part,i) => {
  const start = part.lastIndexOf("{")
  const end = part.lastIndexOf("}")
  if (start !=-1) {
    if ((start > end) || end === -1) {
      return part "d";
    }
  }
  return part
}).join("frac")

console.log(newLat)

  • Related