替换字符串中的前 N ​​个出现

Sys*_*ter 6 javascript regex replace node.js

如何替换N以下字符串中第一次出现的多个空格和制表符:

07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js
Run Code Online (Sandbox Code Playgroud)

我期待以下结果:

07/12/2017|11:01|AM|21523|filename with s p a c  e  s.js
Run Code Online (Sandbox Code Playgroud)

我只通过N在同一个字符串上调用替换时间来知道不是很优雅的选项

.replace(/\s+/, "|").replace(/\s+/, "|").replace(/\s+/, "|");
Run Code Online (Sandbox Code Playgroud)

值得一提的是,我将在近 1,000,000 行上运行它,因此性能很重要。

Der*_*會功夫 7

大概是这样的:

var txt = "07/12/2017  11:01 AM             21523 filename with s p a c  e  s.js";

var n = 0, N = 4;
newTxt = txt.replace(/\s+/g, match => n++ < N ? "|" : match);

newTxt; // "07/12/2017|11:01|AM|21523|filename with s p a c  e  s.js"
Run Code Online (Sandbox Code Playgroud)


bla*_*125 1

我会选择这样的东西。虽然我有点喜欢德里克的回答,所以我会查找他的答案并了解他/她在其中做了什么。

var mytext = "some text separated by spaces and spaces and more spaces";
var iterationCount = 4;
while(iterationCount > 0)
  {
    mytext = mytext.replace(" ", "");
    iterationCount--;
  }
return mytext;
Run Code Online (Sandbox Code Playgroud)