jQuery text() function loses line breaks in IE

荒凉一梦 提交于 2019-11-29 07:01:52
Matthew O'Riordan

Here is a far simpler solution to convert any HTML into plain text with line breaks based on the use of <br> or <p> tags.

function htmlDecodeWithLineBreaks(html) {
  var breakToken = '_______break_______',
      lineBreakedHtml = html.replace(/<br\s?\/?>/gi, breakToken).replace(/<p\.*?>(.*?)<\/p>/gi, breakToken + '$1' + breakToken);
  return $('<div>').html(lineBreakedHtml).text().replace(new RegExp(breakToken, 'g'), '\n');
}

For example, calling the following method:

htmlDecodeWithLineBreaks('line 1<br>line &amp; 2<br />' + 
  'line &gt; 3<p>paragraph 1</p>line 4')

returns:

line 1
line & 2
line > 3
paragraph 1
line 4

Hope that helps ;)

I think something like this will work for you. http://jsfiddle.net/6qbxn/2/. I tested this in IE 7 & 8 & FF 4.0b7 and it works as expected.

JS:

var withBRs = $('#brText').html();
var textWithBreaks = withBRs.replace(/\<br\>/gi,'\r');
$('#area').text(textWithBreaks);

HTML:

<HTML>
<body>
    <div id="brText">Hello <br>How<br>Are<br>You?</div>
    <textarea rows="10" id="area">

    </textarea>
</body>

Edit: This addresses your second bullet point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!