[英]Replace or remove nth occurrence of \n
This is my string: 这是我的字符串:
var ok = "\n\n33333333333\n\n\n";
How to replace the 4th occurence of '\\n' with ''? 如何用''替换'\\ n'的第四次出现? Or, how to remove the 4th occurence of '\\n'?
或者,如何删除“ \\ n”的第四次出现?
replace the entire match with the captured submatch, and the replacement character/string 将整个匹配项替换为捕获的子匹配项,并替换字符/字符串
"AA33333333333AAA".replace(/((?:[^A]*A){3}[^A]*)A/,"$1k")
(with A
and k
insteead of \\n
and ""
so you can more clearly see the results) (使用
\\n
和""
A
和k
insteead,这样您可以更清楚地看到结果)
Here's what, at least to me, is a fine readable solution: 至少对我来说,这是一个易于阅读的解决方案:
var i = 0;
ok = ok.replace(/\n/g, function () {
return ++i == 4 ? "" : "\n";
});
However, it might not win as far as performance is concerned. 但是,就性能而言,它可能不会赢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.