簡體   English   中英

將 \r\n 替換為 < br /> 作為文本

[英]replace \r\n with < br /> as text

嘗試 2 小時將 \r\n 替換為 < br/> 但這似乎是不可能的。
我不知道我在做什么! 請幫忙!

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)

涵蓋所有可能的換行符組合。

String tmp = s.replaceAll("\r\n", "<br>"); // Windows
tmp = tmp.replaceAll("\r", "<br>");        // Old MAC
return tmp.replaceAll("\n", "<br>");       // Linux / UNIX

只需這樣做:

text.replace(/\r\n/g, '<br/>');

你可以試試:

(text+ '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');

您的代碼有很多問題:

  1. String.prototype.replace只替換第一次出現的字符串。 您需要使用帶有/g標志的正則表達式參數來替換所有匹配項。
  2. 轉義使用反斜杠,而不是正斜杠:使用\r\n ,而不是/r/n
  3. checkText返回一個string ,但是您的呼叫站點對返回的字符串不做任何事情 - 它只是被丟棄了。 字符串在 JavaScript 中是不可變的。

我不建議使用字符串來保存 HTML,因為它可以(非常容易)導致 HTML 注入(包括<script> -injection)攻擊。

相反,請執行以下操作之一:

  • 使用String.prototype.split並對數組中的每個string進行 HTML 編碼,並使用"<br />" join
  • 使用.textContent將字符串直接添加到文檔中(不再使用innerText ),並為父元素提供 CSS 樣式的whitespace: pre-wrap; .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM