jQuery javascript regex Replace
with \n

前端 未结 5 508
独厮守ぢ
独厮守ぢ 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:20

    myString.replace(/<br ?\/?>/g, "\n")

    0 讨论(0)
  • 2020-12-02 12:37

    Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:

    <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>
    
    0 讨论(0)
  • 2020-12-02 12:38
    var str = document.getElementById('mydiv').innerHTML;
    document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
    

    or using jQuery:

    var str = $("#mydiv").html();
    var regex = /<br\s*[\/]?>/gi;
    $("#mydiv").html(str.replace(regex, "\n"));
    

    example

    edit: added i flag

    edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

    0 讨论(0)
  • 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 <br> elements, insert raw text with new line character and then remove the <br> 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');
    
    0 讨论(0)
  • 2020-12-02 12:44

    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/

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