Amin
Amin

Reputation: 3

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?

Upvotes: 0

Views: 43

Answers (1)

mplungjan
mplungjan

Reputation: 178350

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)

Upvotes: 0

Related Questions