jQuery javascript regex Replace
with \n

前端 未结 5 553
独厮守ぢ
独厮守ぢ 2020-12-02 11:46

How do i write a regex to replace
or
with \\n. I\'m trying to move text from div to textarea, but don\'t want

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 12:41

    True jQuery way if you want to change directly the DOM without messing with inner HTML:

    $('#text').find('br').prepend(document.createTextNode('\n')).remove();

    Prepend inserts inside the element, before() is the method we need here:

    $('#text').find('br').before(document.createTextNode('\n')).remove();
    

    Code will find any
    elements, insert raw text with new line character and then remove the
    elements.

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

提交回复
热议问题