在没有正则表达式的情况下替换所有内容,我可以在哪里使用 G

Replace all without a regex where can I use the G

本文关键字:我可以 在哪里 正则表达式 情况下 替换      更新时间:2023-09-26

所以我有以下内容:

var token = '[token]';
var tokenValue = 'elephant';
var string = 'i have a beautiful [token] and i sold my [token]';
string = string.replace(token, tokenValue);

以上内容只会替换第一个[token],而不管第二个。

如果我使用正则表达式,我可以像这样使用它

string = string.replace(/[token]/g, tokenValue);

这将取代我所有的[tokens]

但是我不知道如何在不使用//的情况下做到这一点

我发现拆分/连接在大多数情况下都足够令人满意。一个现实生活中的例子:

myText.split("'n").join('<br>');

为什么每次出现令牌时都用 do while 循环替换令牌?

var index = 0;
do {
    string = string.replace(token, tokenValue);
} while((index = string.indexOf(token, index + 1)) > -1);
string = string.replace(new RegExp("''[token'']","g"), tokenValue);
注意接受

的答案,replaceWith 字符串可以包含 inToReplace 字符串,在这种情况下将有一个无限循环......

这里有一个更好的版本:

function replaceSubstring(inSource, inToReplace, inReplaceWith)
{
    var outString = [];
    var repLen = inToReplace.length;
    while (true)
    {
        var idx = inSource.indexOf(inToReplace);
        if (idx == -1)
        {
            outString.push(inSource);
            break;
        }
        outString.push(inSource.substring(0, idx))
        outString.push(inReplaceWith);
        inSource = inSource.substring(idx + repLen);
    }
    return outString.join("");
}
不幸的是,

由于 Javascript 的字符串replace()函数不允许你从特定的索引开始,并且没有办法对字符串进行就地修改,所以很难像在更理智的语言中那样有效地做到这一点。

  • .split().join()不是一个好的解决方案,因为它涉及创建字符串负载(尽管我怀疑 V8 做了一些黑暗魔法来优化这一点(。
  • 在循环中调用replace()是一个糟糕的解决方案,因为 replace 每次都从字符串的开头开始搜索。这将导致 O(N^2( 行为!它还存在无限循环的问题,如此处的答案中所述。
  • 如果您的替换字符串是编译时常量,则正则表达式可能是最好的解决方案,但如果不是,那么您就不能真正使用它。您绝对不应该尝试通过转义将任意字符串转换为正则表达式。

一种合理的方法是使用适当的替换来构建一个新字符串:

function replaceAll(input: string, from: string, to: string): string {
  const fromLen = from.length;
  let output = "";
  let pos = 0;
  for (;;) {
    let matchPos = input.indexOf(from, pos);
    if (matchPos === -1) {
      output += input.slice(pos);
      break;
    }
    output += input.slice(pos, matchPos);
    output += to;
    pos = matchPos + fromLen;
  }
  return output;
}

我将其与所有其他解决方案进行了基准测试(除了在循环中调用replace(),这将是可怕的(,它比正则表达式略快,大约是 split/join 的两倍。

编辑:这几乎与Stefan Steiger的答案相同,由于某种原因我完全错过了。然而,由于某种原因,他的回答仍然使用 .join(),这使得它比我的慢 4 倍。

"[.token.*] nonsense and [.token.*] more nonsense".replace("[.token.*]", "some", "g");

将产生:

"有些废话,还有一些废话">

我意识到@TheBestGuest的答案不适用于以下示例,因为您最终会陷入无限循环:

var stringSample= 'CIC'; 
var index = 0; 
do { stringSample = stringSample.replace('C', 'CC'); } 
while((index = stringSample.indexOf('C', index + 1)) > -1);

因此,这是我对用TypeScript编写的replaceAll方法的建议:

let matchString = 'CIC';
let searchValueString= 'C';
let replacementString ='CC';
    
matchString = matchString.split(searchValueString).join(replacementString);
     console.log(matchString);