Javascript Line Break Textarea

前端 未结 5 1911
忘掉有多难
忘掉有多难 2020-12-18 22:11

I have a text area that I want to pre-populate with some specific text that includes line breaks. I\'m populating the area onLoad but I can\'t get the line breaks to work c

相关标签:
5条回答
  • 2020-12-18 22:48

    replace like this:

    str.replace(/[\r\n]+/g, '\\\n') %>';
    
    0 讨论(0)
  • 2020-12-18 22:55

    Just use the newline character: \n.

    So, if you want the textarea to look like this:

    This is line 1
    This is line 2

    You would use a string like this:

    "This is line 1\nThis is line 2";
    

    See a demo here: http://jsfiddle.net/MzmBd/

    0 讨论(0)
  • 2020-12-18 23:00

    As stated multiple times, you need the \n character.

    see here: http://jsfiddle.net/XbALv/

    document.getElementById("blah").value = 
    "This" + "\n" +
    "is some" + "\n" +
    "text" + "\n";
    
    0 讨论(0)
  • 2020-12-18 23:08

    i had tried many ways to break a textarea into an array. used this method, it might not be the best.

    using .split('\n') does not remove the break and it will create whitespace or break when insert into database. therefore, i replace it with

    textarea content:
    12345
    6789


    a = a.replace(/\n|\r\n|\r/g, "<br>");
    
    var stringArray = a.split('<br>');
    
    for (var i = 0; i < stringArray.length; i++) {
    var myString = stringArray[i];
    myString = myString.replace('<br>', "");
    
    response.write(myString);
    }
    
    0 讨论(0)
  • 2020-12-18 23:09

    You need to replace line breaks with newline characters: \n

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