jQuery text() function loses line breaks in IE

后端 未结 2 938
囚心锁ツ
囚心锁ツ 2020-12-18 03:04

This is quite a talked about problem on the jQuery forums but I can\'t figure out a solution for my situation.

I have an unordered list with some text elements in th

相关标签:
2条回答
  • 2020-12-18 03:43

    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 ;)

    0 讨论(0)
  • 2020-12-18 03:52

    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.

    0 讨论(0)
提交回复
热议问题