简体   繁体   English

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

[英]Replace all without a regex where can I use the G

So I have the following:所以我有以下几点:

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

The above will only replace the first [token] and leave the second on alone.以上只会替换第一个[token]并留下第二个。

If I were to use regex I could use it like如果我要使用正则表达式,我可以像这样使用它

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

And this would replace all my [tokens]这将取代我所有的[tokens]

However I don't know how to do this without the use of //但是我不知道如何在不使用//情况下做到这一点

I have found split/join satisfactory enough for most of my cases.对于我的大多数情况,我发现拆分/加入足够令人满意。 A real-life example:一个真实的例子:

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

Why not replace the token every time it appears with a do while loop?为什么不用 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);

Caution with the accepted answer, the replaceWith string can contain the inToReplace string, in which case there will be an infinite loop...注意已接受的答案,replaceWith 字符串可以包含 inToReplace 字符串,在这种情况下将出现无限循环......

Here a better version:这里有一个更好的版本:

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("");
}

you can get the first occurance using indexOf: 你可以使用indexOf获得第一次出现:

var index=str.indexOf(token);

and then have a function like this to replace it 然后有一个这样的函数来替换它

String.prototype.replaceAt=function(index, tokenvalue) {
      return this.substr(0, index) + character + this.substr(index+character.length);
   }
"[.token.*] nonsense and [.token.*] more nonsense".replace("[.token.*]", "some", "g");

Will produce:将产生:

"some nonsense and some more nonsense" “一些废话,还有一些废话”

I realized that the answer from @TheBestGuest won't work for the following example as you will end up in an endless loop:我意识到@TheBestGuest 的答案不适用于以下示例,因为您最终会陷入无限循环:

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

So here is my proposition for replaceAll method written in TypeScript:所以这是我对用 TypeScript 编写的 replaceAll 方法的建议:

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

Unfortunately since Javascript's string replace() function doesn't let you start from a particular index, and there is no way to do in-place modifications to strings it is really hard to do this as efficiently as you could in saner languages.不幸的是,由于 Javascript 的 string replace()函数不允许您从特定索引开始,并且无法对字符串进行就地修改,因此很难像在更明智的语言中那样有效地做到这一点。

  • .split().join() isn't a good solution because it involves the creation of a load of strings (although I suspect V8 does some dark magic to optimise this). .split().join()不是一个好的解决方案,因为它涉及创建大量字符串(尽管我怀疑 V8 做了一些黑魔法来优化它)。
  • Calling replace() in a loop is a terrible solution because replace starts its search from the beginning of the string every time.在循环中调用replace()是一个糟糕的解决方案,因为 replace 每次都从字符串的开头开始搜索。 This is going to lead to O(N^2) behaviour!这将导致 O(N^2) 行为! It also has issues with infinite loops as noted in the answers here.如此处的答案中所述,它还存在无限循环问题。
  • A regex is probably the best solution if your replacement string is a compile time constant, but if it isn't then you can't really use it.如果您的替换字符串是编译时常量,则正则表达式可能是最佳解决方案,但如果不是,则您无法真正使用它。 You should absolutely not try and convert an arbitrary string into a regex by escaping things.您绝对应该尝试通过转义将任意字符串转换为正则表达式。

One reasonable approach is to build up a new string with the appropriate replacements:一种合理的方法是使用适当的替换来构建一个新字符串:

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

I benchmarked this against all the other solutions (except calling replace() in a loop which is going to be terrible) and it came out slightly faster than a regex, and about twice as fast as split / join .我将其与所有其他解决方案进行了基准测试(除了在循环中调用replace()会很糟糕),它的结果比正则表达式略快,大约是split / join两倍。

Edit: This is almost the same method as Stefan Steiger's answer which I totally missed for some reason.编辑:这与 Stefan Steiger 的答案几乎相同,我出于某种原因完全错过了。 However his answer still uses .join() for some reason which makes it 4 times slower than mine.然而,出于某种原因,他的回答仍然使用.join() ,这使它比我的慢 4 倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用正则表达式替换字符串中的所有关键字吗? (Python) - Can I use regex to replace all keywords in a string? (Python) 如何使用正则表达式获取特定字符后的所有字符,例如逗号(“,”) - How can I use regex to get all the characters after a specific character, e.g. comma (“,”) 如何使用正则表达式将变量替换为计算字符串中的值? - How can I use regex to replace variables by their value in a calculation string? 如何使用正则表达式替换价格中的最后一个逗号? - How can I use regex to replace the last comma in a price? 如何在没有 /g 的情况下替换 JavaScript 中字符串中的所有句点? - How to replace all periods in a string in JavaScript without /g? 如何使用正则表达式匹配没有双字符的字符串 - How can I use regex to match a string without double characters 如何克隆div并使用regEx而不再次克隆? - How can I clone a div and use an regEx without cloning again? 如何使用 Regex 匹配此字符串中的所有 Urls? - How Can I Use Regex to Match All the Urls in This String? 正则表达式:替换不包含逗号的两个字符之间的所有字符 - Regex: replace all between two characters where no comma is included 有没有一种方法可以使用正则表达式来替换我作为字符串读取的文件中匹配的一部分? - Is there a way I can use regex to replace only part of a match in a file that i'm reading in as a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM