There are two ways to add a carriage return character in JavaScript: using the "\n" character or the String.fromCharCode(10) method. Use the "\n" character to insert a newline character directly into the string, and use the String.fromCharCode(10) method to convert Unicode code point 10 to a carriage return character.
How to add a carriage return to a JavaScript string
In JavaScript, you can use \n
character or String.fromCharCode(10)
method adds a carriage return to the string.
Using the \n
characters
The easiest way is to use the \n
characters directly in the string. This creates a newline character in the string, splitting the text into two lines. For example:
const str = "Hello\nWorld"; console.log(str); // 输出:Hello // World
Use the String.fromCharCode(10)
method
##String.fromCharCode(10) method to Converts a given Unicode code point to the corresponding character. The Unicode code point for carriage return is 10, so we can add carriage return using the following code:
const str = "Hello" + String.fromCharCode(10) + "World"; console.log(str); // 输出:Hello // World
Example
The following is a string in JavaScript Specific example of adding a carriage return:// 创建一个字符串 const str = "This is a long string"; // 使用 `\n` 字符添加回车 const newStr = str.replace("long", "long\nstring"); // 使用 `String.fromCharCode(10)` 方法添加回车 const anotherNewStr = str.substring(0, 10) + String.fromCharCode(10) + str.substring(10); // 输出更改后的字符串 console.log(newStr); // 输出:This is a long // string console.log(anotherNewStr); // 输出:This is a // long string
The above is the detailed content of How to add carriage return to string in js. For more information, please follow other related articles on the PHP Chinese website!