Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!