textarea中的换行标记

时间:2016-04-06 14:51:52

标签: javascript jquery regex

   <script>
        $('#textarea_').on('keyup', function () {
            var textareaContentWithJquery = $('#textarea_').val();
            var textareaContentWithJavascript = document.getElementById('textarea_').value;
        });
    </script>

        <textarea cols="20" id="textarea_" name="textarea_" rows="2">
Some text in textarea here is created without pressing enter, 
just plain text. But how can i get the position 
of  newline markup from textarea so that i can put <br> there? 
        </textarea>

我从textarea那里得到了价值(纯文本); 这里的textarea中的一些文本是在不按Enter键的情况下创建的,只是纯文本。但是我怎样才能从textarea获得换行标记的位置,以便我可以将<br>放在那里?

如果我按下输入textarea并转到新行,那么这将很容易,因为在我按下回车的位置会有一个\n但是当我只是添加文本并让textarea包裹文本到新行然后我在文本中没有\n

我需要它像这样(不是纯文本);

Some text in textarea here is created without pressing enter,\n
just plain text. But how can i get the position\n
of  newline markup from textarea so that i can put <br> there?\n

So i would easily replace \n with <br> 
Some text in textarea here is created without pressing enter,<br> 
just plain text. But how can i get the position<br> 
of  newline markup from textarea so that i can put <br> there? <br>

textareaContentWithJquery和textareaContentWithJavascript给出了相同的结果,我的意思是没有\n标记。所以它们毫无用处。

2 个答案:

答案 0 :(得分:1)

您可以使用&#013;作为新行,然后搜索\n并替换为<br>

 <textarea cols="20" id="textarea_" name="textarea_" rows="12" cols="150">
    Some text in textarea here is created without pressing enter, just plain text. 
    But how can i get the position of newline markup from textarea so that i can put <br>&#013; there? 
 </textarea>

$('#textarea_').on('keyup', function () {
   var textareaContentWithJquery = $('#textarea_').val();                  
   console.log(textareaContentWithJquery.replace(/\n/g, "<br>"));
});

更新了codepen:http://codepen.io/nobrien/pen/QNmOpv

答案 1 :(得分:0)

试试这个

$('#textarea_').on('keyup', function () {
   var textareaContentWithJquery = $('#textarea_').val();                  
   console.log(textareaContentWithJquery.replace(/\r?\n/g, '<br />'));
});
相关问题