Home >Web Front-end >HTML Tutorial >How to handle the newline character '↵' in html

How to handle the newline character '↵' in html

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-04-25 09:26:033270browse

This article will introduce to you how to deal with the newline character "↵" in HTML. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to handle the newline character '↵' in html

Requirement background

Request the field value back through ajax. The character is of String type and contains the newline character , which will be obtained The obtained string content is displayed in the original format with line breaks.

Solution idea

Solve the problem by replacing elements with strings

Solution process

[danger] Error process: Think of replacing elements with strings In the first attempt, the <br> tag was always used to replace the characters, but the replacement failed.

The correct solution

var myString = myString.replace(/(\r\n|\n|\r)/gm, "<br />");

[info] is not replaced by , but will be recognized as \r,\ in html n and other escape characters, so you need to use \r\n to replace them.

Test example

<body>
	<p id="app"></p>
	<p id="app2"></p>
	<script type="text/javascript">
		var  msg = `你好
		换行符
		这是一个非常有意思的替换`;
		var msg2 = msg.replace(/(\r\n|\n|\r)/gm , "<br />");
		document.getElementById("app").innerHTML = msg;
		document.getElementById("app2").innerHTML = msg2;
		console.log(msg)
		console.log(msg2 )
	</script>
</body>

Display results<br>How to handle the newline character ↵ in html

Important note: The line break ↵ must be entered through the keyboard, not for the purpose of testing the effect. The ↵ character.

Recommended learning: html video tutorial

The above is the detailed content of How to handle the newline character '↵' in html. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete