简体   繁体   English

如何更换 <br/> 标记\\ n(换行)

[英]How to replace <br/> tag with the \n(new line) in jquery

I use this code snippets to replace <br/> tag with the "\\n"(new line) in jquery. 我使用此代码段在jquery中将<br/>标记替换为“ \\ n”(新行)。 But it did not work 但这没用

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

But it did not work why is that? 但这为什么没有用?

.replace() does not change the contents itself. .replace()不会更改内容本身。 It returns a new string so if you want to use that new string, you have to put the return value from .replace() somewhere. 它返回一个新字符串,因此,如果要使用该新字符串,则必须将.replace()的返回值放在某个位置。

You may also need to fix your regex if you're targeting <br\\> by escaping the \\ and making it optional. 如果您要定位<br\\> ,请转义\\并将其设为可选,从而可能需要修复正则表达式。

FYI, in HTML a \\n doesn't do anything so if you're just trying to remove all <br> tags in #UserTextArea , you can just use the DOM parser to do this: 仅供参考,在HTML中\\n不会执行任何操作,因此,如果您只是尝试删除#UserTextArea中的所有<br>标记, #UserTextArea可以使用DOM解析器执行此操作:

$("#UserTextArea br").remove();

Or, if you just want to get the string with <br> tags replaced into a variable that you can use for something else, you can do this: 或者,如果您只想将替换了<br>标记的字符串替换为可以用于其他用途的变量,则可以执行以下操作:

var str = $("#UserTextArea").html().replace(/\<br\\?>/g, "\n");

Or, you're string to remove <br> form data.projectDescription and assign it as he HTML to #UserTextArea , you can do this: 或者,您需要删除<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'));

Or, to search and replace the inner HTML of an element: 或者,要搜索并替换元素的内部HTML:

var $element = $('#UserTextArea');
var html = $element.html();
$element.html(html.replace(/\<br\s*\>/g, '\n'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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