replacestring中的前N个事件

如何replace下列string中的前N空格和制表符:

 07/12/2017 11:01 AM 21523 filename with space s.js 

我期待以下结果:

 07/12/2017|11:01|AM|21523|filename with space s.js 

我只知道通过在同一个string上调用N次取代,我知道不是很优雅的选项

 .replace(/\s+/, "|").replace(/\s+/, "|").replace(/\s+/, "|"); 

值得一提的是,我将在近100万行上运行这样的performance很重要。

可能是这样的:

 var txt = "07/12/2017 11:01 AM 21523 filename with space 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 space s.js" 

你可以拿一个柜台,并减less它。

 var string = '07/12/2017 11:01 AM 21523 filename with space s.js', n = 4, result = string.replace(/\s+/g, s => n ? (n--, '|') : s); console.log(result); 

我会去这样的事情。 虽然我有点像德里克的回答,所以我会看他的,并了解他/她在做什么。

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

Derek和Nina为dynamicreplaceN个空白组提供了很好的答案。 如果N是静态的,则可以使用非空白符号( \S )来匹配和保持组之间的空白:

.replace(/\s+(\S+)\s+(\S+)\s+/, '|$1|$2|')

你自己的解决scheme的recursion版本呢?

 function repalceLeadSpaces(str, substitution, n) { n = n || 0; if (!str || n <= 0) { return str; } str = str.replace(/\s+/, substitution); return n === 1 ? str : repalceLeadSpaces(str, substitution, n - 1) } 

这里的一些答案已经很好了,但是既然你说你想要速度,那么我会一起去做,就像这样:

 var logLine = '07/12/2017 11:01 AM 21523 filename with space s.js'; var N = 4; while(--N + 1){ logLine = logLine.replace(/\s+/, '|'); } console.log(logLine);