How do i write a regex to replace <br /> or <br> with \n. I'm trying to move text from div to textarea, but don't want <br>'s to show in the textarea, so i want to replace then with \n.

推荐答案

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");

or using jQuery:

var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));

example

edit:增加了i个旗帜

edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

Jquery相关问答推荐

为什么函数没有进入

jQuery函数从数组中获取所有唯一元素?

如何在 jQuery 中使用:not 和 hasClass() 来获取没有类的特定元素

在 jQuery UI Datepicker 中禁用future 日期

如何立即启动 setInterval 循环?

如何禁用在div内单击

如何在 JQuery UI 自动完成中使用 source:function()... 和 AJAX

如何使用 jquery 正确格式化货币?

Zepto 和 jQuery 2 有什么区别?

你如何获得文本区域中的光标位置?

删除索引后的所有项目

Select 除第一个之外的所有子元素

使用 JQuery / JavaScript 调用/单击 mailto 链接

在jQuery中添加ID?

带有函数的 JavaScript 三元运算符示例

jquery可排序占位符高度问题

如何使用 JQuery $.scrollTo() 函数滚动窗口

$.getJSON 在 IE8 中返回缓存数据

在事件中使用 jQuery 获取被点击的元素?

用于发布和获取的 Ajax 教程