js正则实现换行
使用正则表达式匹配换行符
在JavaScript中,换行符可以通过正则表达式匹配。常见的换行符包括\n(换行)、\r(回车)以及\r\n(Windows换行)。
const text = "第一行\n第二行\r第三行\r\n第四行";
const lines = text.split(/\r?\n|\r/);
console.log(lines); // ["第一行", "第二行", "第三行", "第四行"]
正则表达式替换换行符
如果需要将换行符替换为其他字符(例如HTML的<br>标签),可以使用String.prototype.replace方法。

const text = "第一行\n第二行\r第三行\r\n第四行";
const htmlText = text.replace(/\r?\n|\r/g, "<br>");
console.log(htmlText); // "第一行<br>第二行<br>第三行<br>第四行"
匹配多行文本
使用正则表达式的m标志(多行模式),可以匹配每行的开头或结尾。

const multiLineText = "Line 1\nLine 2\nLine 3";
const regex = /^Line/gm;
const matches = multiLineText.match(regex);
console.log(matches); // ["Line", "Line", "Line"]
匹配空白行
空白行通常由连续的换行符组成,可以通过正则表达式匹配并移除。
const textWithEmptyLines = "Line 1\n\nLine 2\n \nLine 3";
const cleanedText = textWithEmptyLines.replace(/^\s*[\r\n]/gm, "");
console.log(cleanedText); // "Line 1\nLine 2\nLine 3"
跨平台换行符处理
不同操作系统使用不同的换行符(\n、\r\n或\r),可以通过正则表达式统一处理。
const crossPlatformText = "Line 1\r\nLine 2\nLine 3\rLine 4";
const normalizedText = crossPlatformText.replace(/\r\n|\r|\n/g, "\n");
console.log(normalizedText); // "Line 1\nLine 2\nLine 3\nLine 4"






