[英]replace \r\n with < br /> as text
Trying for 2 hours to replace \r\n with < br/> but it seems to be impossible.尝试 2 小时将 \r\n 替换为 < br/> 但这似乎是不可能的。
I don't know what i'm doing!我不知道我在做什么! Please help!
请帮忙!
const text = '"Hello!\r\n\r\nThis is a dog!'
const checkText = str=> {
const match = /\r|\n/.exec(text);
if (match) {
//return str.replace(/(?:\\[rn]|[\r\n]+)+/g, '<br/>');
return str.replace('/r/n', '<br/>');
}
return str;
};
checkText(text)
Covering all the possible new line character combinations.涵盖所有可能的换行符组合。
String tmp = s.replaceAll("\r\n", "<br>"); // Windows
tmp = tmp.replaceAll("\r", "<br>"); // Old MAC
return tmp.replaceAll("\n", "<br>"); // Linux / UNIX
Just do this:只需这样做:
text.replace(/\r\n/g, '<br/>');
You may try:你可以试试:
(text+ '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
There are multiple things wrong with your code:您的代码有很多问题:
String.prototype.replace
only replaces the first occurrence of a string. String.prototype.replace
只替换第一次出现的字符串。 You need to use a regex argument with the /g
flag to replace all occurrences./g
标志的正则表达式参数来替换所有匹配项。\r\n
, not /r/n
.\r\n
,而不是/r/n
。checkText
returns a string
, but your call-site doesn't do anything with the returned string - it's just dropped. checkText
返回一个string
,但是您的呼叫站点对返回的字符串不做任何事情 - 它只是被丢弃了。 Strings are immutable in JavaScript. I don't recommend using strings to hold HTML because it can (very easily) cause HTML-injection (including <script>
-injection) attacks.我不建议使用字符串来保存 HTML,因为它可以(非常容易)导致 HTML 注入(包括
<script>
-injection)攻击。
Instead, do one of the following:相反,请执行以下操作之一:
String.prototype.split
and HTML-encode each string
in the array and join
with "<br />"
.String.prototype.split
并对数组中的每个string
进行 HTML 编码,并使用"<br />"
join
。.textContent
(don't use innerText
anymore) and give the parent element the CSS style whitespace: pre-wrap;
.textContent
将字符串直接添加到文档中(不再使用innerText
),并为父元素提供 CSS 样式的whitespace: pre-wrap;
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.