简体   繁体   English

将 \r\n 替换为 < br /> 作为文本

[英]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:您的代码有很多问题:

  1. 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标志的正则表达式参数来替换所有匹配项。
  2. Escapes use a backslash, not a forward slash: Use \r\n , not /r/n .转义使用反斜杠,而不是正斜杠:使用\r\n ,而不是/r/n
  3. 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.字符串在 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:相反,请执行以下操作之一:

  • Use String.prototype.split and HTML-encode each string in the array and join with "<br />" .使用String.prototype.split并对数组中的每个string进行 HTML 编码,并使用"<br />" join
  • Add the string directly to the document with .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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM