没有正则表达式替换所有我可以使用G

Net*_*eta 10 javascript regex replace

所以我有以下内容:

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

以上只会取代第一个[token]而只留下第二个.

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

string = string.replace(/[token]/g, tokenValue);
Run Code Online (Sandbox Code Playgroud)

而这将取代我所有的 [tokens]

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

pil*_*lat 18

对于我的大多数情况,我发现分裂/加入足够令人满意.一个真实的例子:

myText.split("\n").join('<br>');
Run Code Online (Sandbox Code Playgroud)


小智 9

为什么不在每次出现do while循环时更换令牌?

var index = 0;
do {
    string = string.replace(token, tokenValue);
} while((index = string.indexOf(token, index + 1)) > -1);
Run Code Online (Sandbox Code Playgroud)

  • 这将不起作用:`var strinSample ='CIC'; var index = 0; 做{strinSample = strinSample.replace('C','CC'); } while(((index = strinSample.indexOf('C',index + 1))&gt; -1);` (2认同)