2022-07-03 11:16:33
在 JavaScript 中,可以通过以下两种方法为字符串添加回车(换行符):
方法 1:使用 n 字符直接在字符串中插入 n 字符,这是最简单且常用的方式。n 是换行符的转义序列,会在输出时将文本分成两行。
const str = "HellonWorld";console.log(str); // 输出:// Hello// World方法 2:使用 String.fromCharCode(10)通过 String.fromCharCode(10) 方法将 Unicode 码点 10(对应换行符)转换为字符并插入字符串中。
const str = "Hello" + String.fromCharCode(10) + "World";console.log(str); // 输出:// Hello// World实际应用示例以下是一个具体示例,展示如何在字符串中动态添加回车:
// 原始字符串const str = "This is a long string";// 使用 `n` 替换部分内容并添加回车const newStr = str.replace("long", "longnstring");console.log(newStr); // 输出:// This is a long// string// 使用 `String.fromCharCode(10)` 在指定位置插入回车const anotherNewStr = str.substring(0, 10) + String.fromCharCode(10) + str.substring(10);console.log(anotherNewStr); // 输出:// This is a// long string注意事项显示效果依赖环境:
在 HTML 中,n 不会直接渲染为换行,需配合 <pre> 标签或 CSS 的 white-space: pre 属性。
在控制台或文本文件中,n 会正常换行。
跨平台兼容性:
Windows 系统通常使用 rn(回车+换行),而 Unix/Linux 和 macOS 仅用 n。如需严格兼容,可检测环境或统一使用 n。
模板字符串:在模板字符串(反引号 `)中,可直接按回车键换行,无需转义符:
const multiLineStr = `This isa multi-linestring`;