Home > Net >  Finding the index of several identical words
Finding the index of several identical words

Time:01-05

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?

CodePudding user response:

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, string, offset) {
  pos.push(offset)
  return match.replace(/frac(. ?)}/g,"$1}/")
})
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)

  •  Tags:  
  • Related