Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 }/

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading