【发布时间】:2012-08-08 06:12:11
【问题描述】:
我使用此代码 sn-ps 将 <br/> 标记替换为 jquery 中的“\n”(新行)。但它没有工作
$("#UserTextArea").html(data.projectDescription).replace(/\<br\>/g, "\n");
但它不起作用,这是为什么?
【问题讨论】:
标签: javascript jquery jsp-tags
我使用此代码 sn-ps 将 <br/> 标记替换为 jquery 中的“\n”(新行)。但它没有工作
$("#UserTextArea").html(data.projectDescription).replace(/\<br\>/g, "\n");
但它不起作用,这是为什么?
【问题讨论】:
标签: javascript jquery jsp-tags
.replace() 不会更改内容本身。它返回一个新字符串,所以如果你想使用这个新字符串,你必须把.replace()的返回值放在某个地方。
如果您的目标是 <br\>,您可能还需要通过转义 \ 并将其设为可选来修复您的正则表达式。
仅供参考,在 HTML 中 \n 没有任何作用,因此如果您只是想删除 #UserTextArea 中的所有 <br> 标记,您可以使用 DOM 解析器来执行此操作:
$("#UserTextArea br").remove();
或者,如果您只想将带有 <br> 标记的字符串替换为可用于其他用途的变量,您可以这样做:
var str = $("#UserTextArea").html().replace(/\<br\\?>/g, "\n");
或者,您可以从data.projectDescription 中删除<br> 并将其作为HTML 分配给#UserTextArea,您可以这样做:
$("#UserTextArea").html(data.projectDescription..replace(/\<br\\?>/g, "\n"));
【讨论】:
$("#UserTextArea").html(data.projectDescription.replace(/\<br[\/]*\>/g, "\n"));
【讨论】:
data.projectDescription的内容是什么?
$('#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'));
【讨论】: