简体   繁体   English

替换或删除第n个\\ n

[英]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”的第四次出现?

  • find n-1 occurences and other characters. 查找n-1次出现和其他字符。
  • capture the submatch. 捕获子匹配。
  • find the next occurence. 找到下一个事件。
  • 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"" Ak 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM