[英]jQuery javascript regex Replace <br> with \n
How do i write a regex to replace <br />
or <br>
with \\n
. 如何用
\\n
来编写正则表达式来替换<br />
或<br>
。 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
. 我正在尝试将文本从div移动到textarea,但不希望
<br>
在textarea中显示,所以我想用\\n
替换。
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
<br class="clear" />
/<br[^>]*>/gi
来匹配br
和slash
之间的任何东西,如果你有例如<br class="clear" />
myString.replace(/<br ?\\/?>/g, "\\n")
True jQuery way if you want to change directly the DOM without messing with inner HTML: 如果你想直接改变DOM而不搞乱内部HTML,那就是真正的jQuery方式:
$('#text').find('br').prepend(document.createTextNode('\\n')).remove();
$( '#文字')找到( 'BR')预定(document.createTextNode( '\\ n'))删除()。;
Prepend inserts inside the element, before() is the method we need here: 将insert插入到元素内部,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');
a cheap and nasty would be: 一个廉价和讨厌的将是:
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/
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.