[英]How to replace <br/> tag with the \n(new line) in jquery
我使用此代碼段在jquery中將<br/>
標記替換為“ \\ n”(新行)。 但這沒用
$("#UserTextArea").html(data.projectDescription).replace(/\<br\>/g, "\n");
但這為什么沒有用?
.replace()
不會更改內容本身。 它返回一個新字符串,因此,如果要使用該新字符串,則必須將.replace()
的返回值放在某個位置。
如果您要定位<br\\>
,請轉義\\並將其設為可選,從而可能需要修復正則表達式。
僅供參考,在HTML中\\n
不會執行任何操作,因此,如果您只是嘗試刪除#UserTextArea
中的所有<br>
標記, #UserTextArea
可以使用DOM解析器執行此操作:
$("#UserTextArea br").remove();
或者,如果您只想將替換了<br>
標記的字符串替換為可以用於其他用途的變量,則可以執行以下操作:
var str = $("#UserTextArea").html().replace(/\<br\\?>/g, "\n");
或者,您需要刪除<br>
表單data.projectDescription
並將其作為HTML分配給#UserTextArea
,您可以執行以下操作:
$("#UserTextArea").html(data.projectDescription..replace(/\<br\\?>/g, "\n"));
$("#UserTextArea").html(data.projectDescription.replace(/\\<br[\\/]*\\>/g, "\\n"));
$('#UserTextArea').html(data.projectDescription.replace(/\<br\s*\>/g, '\n'));
或者,要搜索並替換元素的內部HTML:
var $element = $('#UserTextArea');
var html = $element.html();
$element.html(html.replace(/\<br\s*\>/g, '\n'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.