查找几个相同单词的索引

Finding the index of several identical words

我有一个像这样的 LaTeX 字符串

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

我想在字符串中找到“frac”的索引并将它们放入一个数组中然后我想在“frac”之后找到第一个'}'字符并将其替换为“}/”最后从字符串中删除“frac”。

我使用了这段代码,但当我们有一个“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)

输出: \{x}//{2}+\{3}{x}

谁能帮我改进我的代码?

是这样的吗?

frac(.+?)}

是字面 frac 后跟一个捕获组,它将捕获一个或多个任何东西 .+ 直到 } 并将其替换为任何东西加上 }/

使用函数replacement抓索引替换

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)

使用两组代码的旧答案

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,"}/")
console.log(pos)
console.log(newRes)