替换字符串中的前N个出现次数 [英] Replace First N Occurrences in the String

查看:79
本文介绍了替换字符串中的前N个出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I replace first N occurrences of many whitespaces and tabs in the following string:

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

我只知道通过调用replace N 相同字符串上的次数

I know not very elegant option only via calling replace N times on the same string

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

值得一提的是,我将在近1,000,000行运行此项,因此性能至关重要。

Worth to mention that I'm going to run this on near 1,000,000 lines so performance matters.

推荐答案

你可以拿一个计数器并递减它。

You could take a counter and decrement it.

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。

You could replace the ternary expression with one with logical AND 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);

这篇关于替换字符串中的前N个出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆