如何在 jquery 中将 <br/> 标记替换为 (换行符)

How to replace <br/> tag with the (new line) in jquery

本文关键字:替换 换行符 br jquery 中将      更新时间:2023-09-26

我使用此代码片段将<br/>标记替换为jquery中的"'"(换行符)。但它没有奏效

  $("#UserTextArea").html(data.projectDescription).replace(/'<br'>/g, "'n");

但它没有奏效,为什么呢?

.replace()不会

更改内容本身。 它返回一个新字符串,因此如果要使用该新字符串,则必须将返回值从.replace()放在某个地方。

如果您的目标是 <br'>,则可能还需要通过转义 '' 并将其设置为可选来修复正则表达式。

仅供参考,在 HTML 中,'n 不执行任何操作,因此,如果您只是尝试删除 #UserTextArea 中的所有<br>标签,您可以使用 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'));