[英]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 做了一些黑魔法来优化它)。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! 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.