jQuery javascript regex 将 <br> 替换为 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5959415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery javascript regex Replace <br> with \n
提问by Pinkie
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
.
我如何编写一个正则表达式来替换<br />
或<br>
使用\n
. 我正在尝试将文本从 div 移动到 textarea,但不希望<br>
's 显示在 textarea 中,所以我想将 then 替换为\n
.
回答by Teneff
var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
or using jQuery:
或使用 jQuery:
var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));
edit:added i
flag
编辑:添加i
标志
edit2:you can use /<br[^>]*>/gi
which will match anything between the br
and slash
if you have for example <br class="clear" />
edit2:您可以使用/<br[^>]*>/gi
which 将匹配br
和之间的任何内容slash
,例如<br class="clear" />
回答by Adam Bergmark
myString.replace(/<br ?\/?>/g, "\n")
myString.replace(/<br ?\/?>/g, "\n")
回答by Radek Pech
True jQuery way if you want to change directly the DOM without messing with inner HTML:
真正的 jQuery 方式,如果您想直接更改 DOM 而不会弄乱内部 HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
在元素内部添加插入,before() 是我们这里需要的方法:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
代码将找到任何 <br> 元素,插入带有换行符的原始文本,然后删除 <br> 元素。
This should be faster if you work with long texts since there are no string operations here.
如果您使用长文本,这应该会更快,因为这里没有字符串操作。
To display the new lines:
显示新行:
$('#text').css('white-space', 'pre-line');
回答by James Khoury
a cheap and nasty would be:
一个便宜又讨厌的将是:
jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")
jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")
EDIT
编辑
jQuery("#myTextArea").val(
jQuery("#myDiv").html()
.replace(/\<br\>/g, "\n")
.replace(/\<br \/\>/g, "\n")
);
Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/
如果需要,还创建了一个 jsfiddle:http: //jsfiddle.net/2D3xx/
回答by RobG
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
与 jQuery 没有任何关系,但是如果您想从字符串中修剪模式,请使用正则表达式:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br *\/?>/gi;
ta.value = text.replace(re, '\n');
">Add stuff to text area</button>