在 textarea 行的末尾插入换行符 <br>

时间:2021-04-28 00:34:33

标签: javascript html

我有一个表单(表单中的一个文本区域),它通过 ajax post 请求发送到一个 php 文件。在 php 文件中,我发送了一封包含表单内容的 html 邮件。 textarea 具有固定大小(列数、行数和最大长度)。

这是文本区域:

<textarea class="form-control font-consolas" id="hellotext"
              wrap="hard" cols="36" rows="10" style="width: auto" maxlength="360"
              data-limit-rows="true"
              name="hellotext" required></textarea>

我成功转换了新行:

var hellotext = encodeURIComponent($("#hellotext").val());
hellotext = hellotext.replace(/%0A/g,"<br>");

这是转换文本的示例:

 Hello, this is a short test. Now a NewLine is coming in the word previous NewLine.

 Thaaaaaaaaaaaaaaaaats a short teeeeeeeeeeeeeeeest (new line in teeeeeeest).

 NeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeLine

但是文本应该使每一行在第 36 个字符处成为换行符。当然,不能截断整个单词,但长度超过 36 个字符的单词应该被截断。正如用户在输入中看到的那样: enter image description here

1 个答案:

答案 0 :(得分:0)

为什么不使用可编辑的 div?它会自动打破你想要的线条。鉴于您为接收端提供了正确的样式。例如空白:前行

点击此处了解如何手动将 div 添加到表单中:Getting value from contenteditable div

let editablediv = document.querySelector('div')

function output(str){
  document.querySelector('pre').textContent=str
}

editablediv.addEventListener('keyup',function(event){
  output(event.target.innerText)
} )

let msg = 'Nehemiah 8:10 \n\n Do not grieve, for the joy of the Lord is your strength. Isaiah 41:10 So do not fear, for I am with you; do not be dismayed, for I am your God. I will strengthen you and help you; I will uphold you with my righteous right hand.'

editablediv.textContent=msg
output(msg)
pre{
white-space:pre-line;
width:50%;
}
#ed{
border:1px solid #000;
width:50%;
}
<label for=ed><h3>Editable Div</h3>
Click on the box below to edit it;</label>
<div id=ed contenteditable=true></div>

<h3>Output</h3>
<pre></pre>