如何从字符串中删除重复的 \n (换行符)并只保留一个?

How to remove duplicate \n (line break) from a string and keep only one?

我有这样的字符串:

This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence.

我想要的是:

This is a sentence.\n This is sentence 2.\n This is sentence 3.\n And here is the final sentence.

我想从字符串中删除所有重复的 \n 字符,但只保留一个字符,是否可以像 javascript 中那样做?

您可以尝试将 \n{2,} 替换为单个 \n:

var input = "This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence.";
var output = input.replace(/\n{2,}\s*/g, '\n');
console.log(output);

您可以将正则表达式用作 /\n+/greplace 它与单个 \n

const str =
  "This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence.";
const result = str.replace(/\n+/g, "\n");
console.log(result);