Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Finding the index of several identical words

I have a laTeX string like this

let result = "\\frac{x}{2}+\\frac{3}{x}";

I want to find the index of "frac"s in the string and put them in a array then I want to find the first '}' char after "frac" and replace it with "}/" and finally remove "frac" from the string.

I used this block of code but it just work correctly when we have one "frac"

let result = "\\frac{x}{2}+\\frac{3}{x}";

if (result.indexOf("frac") != -1) {
  for (let i = 0; i < result.split("frac").length; i++) {

    let j = result.indexOf("frac");
    let permission = true;
    while (permission) {

      if (result[j] == "}") {
        result = result.replace(result[j], "}/")
        permission = false;

      }
      j++;

    }
    result = result.replace('frac', '');
  }
}
console.log(result)

OUTPUT: \\{x}//{2}+\\{3}{x}

Could anyone help me to improve my code?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Something like this?

frac(.+?)}

is the literal frac followed by a capture group that will capture one or more of anything .+ until a } and replace it with that anything plus a }/

Using the function replacement to grab index and replace

let result = "\\frac{x}{2}+\\frac{3}{x}";
let pos = [];
const newRes = result.replace(/frac(.+?)}/g,function(match, found, offset,string) {
  console.log(match,found,offset,string)
  pos.push(offset)
  return `${found}/`; // return the found string with the added slash
})
console.log(pos)
console.log(newRes)

Older answer using two sets of code

let result = "\\frac{x}{2}+\\frac{3}{x}";

let re = /frac/gi, res, pos = [];
while ((res = re.exec(result))) {
   pos.push(res.index);
}
const newRes = result.replace(/frac(.+?)}/g,"$1}/")
console.log(pos)
console.log(newRes)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda