2017-11-10 81 views
1

我怎么能代替第一N出现很多空格和选项卡下面的字符串:替换首先n个出现的字符串

07/12/2017 11:01 AM    21523 filename with s p a c e s.js 

我期待以下结果:

07/12/2017|11:01|AM|21523|filename with s p a c e s.js 

我知道不是非常优雅的选项,只能通过呼叫替换N次相同的字符串

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

值得一提的是,我将在近1,000,000行上运行这样的表现很重要。

+1

@stealththeninja欧普希望只替换字符串中的前4次出现,从而在文件名中留下空格完整。 –

+0

'g'将取代一切。但我只需要替换第一个'n'出现 –

+0

就像你可以使用某种循环的气味 –

回答

1

我会去这样的事情。虽然我有点像Derek的回答,所以我会看他的,并理解他/她在其中做了些什么。

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

大概是这样的:

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" 
3

你可以采取一个计数器和递减它。

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

您可以用逻辑AND和OR更换一个三元表达。

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

1

德里克和Nina动态地用N空白组提供了极大的答案。如果N是静态的,非空白令牌(\S)可以用于匹配,并保持各组之间的空白:

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

1

什么递归版本的您自己的解决方案?

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) 
} 
1

一些答案在这里真的好了,但是既然你说你想要的速度,我想用一个单一的,而走,像这样:

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

这里有JSFiddle:https://jsfiddle.net/2bxpygjr/

相关问题