Home >Web Front-end >JS Tutorial >How to add carriage return to string in js

How to add carriage return to string in js

下次还敢
下次还敢Original
2024-05-06 09:27:161108browse

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 carriage return to string in js

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:

<code class="js">const str = "Hello\nWorld";
console.log(str); // 输出:Hello
//          World</code>

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:

<code class="js">const str = "Hello" + String.fromCharCode(10) + "World";
console.log(str); // 输出:Hello
//          World</code>

Example

The following is a string in JavaScript Specific example of adding a carriage return:

<code class="js">// 创建一个字符串
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</code>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn