从textarea获取文本时如何保留换行符? [英] How do I preserve line breaks when getting text from a textarea?

查看:104
本文介绍了从textarea获取文本时如何保留换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击提交时,我得到了textarea的值。然后我把这个值放在页面的其他地方。但是,当我这样做时,它会丢失换行符,使输出变得非常难看。



以下是我正在访问的textarea:

 < textarea id =post-textclass =form-controlrows =3placeholder =What's up?所需>< / textarea的> 

以下是访问帖子并转录它的JavaScript代码。

  var post = document.createElement('p'); 
var postText = document.getElementById('post-text')。value;
post.append(postText);
var card = document.createElement('div');
card.append(post);
var cardStack = document.getElementById('#card-stack');
cardStack.prepend(card);

当输入内容类似于:


小组时间表:



周二练习@ 5楼(晚上8点 - 晚上11点)

周四练习@ 5楼(晚上8点 - 晚上11点)

周日练习@(晚上9点--12点)

blockquote>

输出结果为:


小组排程:星期二练习@ 5楼(晚上8点 - 晚上11点)星期四练习@ 5楼(晚上8点 - 晚上11点)周日练习@(晚上9点至12点)

有没有一种方法可以保留换行符?

解决方案

最简单的解决方案是简单地设置插入文本的元素的样式使用以下CSS属性:

  white-space:pre-wrap; 

这个属性会导致匹配元素中的空格和换行符被用与< textarea> 。也就是说,连续的空格不会被折叠,并且线条在显示的换行符处被破坏(但是如果它们超过元素的宽度,它们也会被自动换行)。

到目前为止在这里发布的答案很容易受到 HTML注入(例如,因为它们将未转义的用户输入分配给 innerHTML )或其他错误,让我举一个例子,说明如何基于原始代码安全正确地执行此操作:



document.getElementById('post-button')。 addEventListener('click',function(){var post = document.createElement('p'); var postText = document.getElementById('post-text')。value; post。追加(postText); var card = document.createElement('div'); card.append(柱); var cardStack = document.getElementById('card-stack'); cardStack.prepend(card);});

#card -stack p {background:#ddd;白色空间:预包装; / *< - 这保留了行分隔符* /} textarea {width:100%;}

 < textarea id =post-textclass =form-controlrows =8placeholder =What's up? (晚上8点 - 晚上11点)周日练习@(9pm  -  12 am)< / textarea>< br>< br><输入类型= buttonid =post-buttonvalue =Post!>< div id =card-stack>< / div>  

<请注意,就像你原来的代码一样,上面的代码片段使用

https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/appendrel =noreferrer> append() prepend() 。在撰写本文时,这些功能仍然被认为是实验性的,并且不被所有浏览器完全支持。如果您想保持安全并与旧版浏览器保持兼容,您可以很容易地将它们替换为以下内容:


  • element.append(otherElement)可以替换为 element.appendChild(otherElement);

  • element.prepend(otherElement)可以替换为 element.insertBefore(otherElement,element.firstChild);

  • element.append(stringOfText)可以替换为 element.appendChild(document.createTextNode(stringOfText))
  • element.prepend(stringOfText)可以替换为 element.insertBefore(document。 createTextNode(stringOfText),element.firstChild);

  • 作为一个特例,如果元素为空, element.append(stringOfText) element.prepend(stringOfText)可以简单地替换为 element.textContent = stringOfText



与上面相同,但不使用 append() prepend()



#card-stack p {background:#ddd;白色空间:预包装; / *< - 这保留了行分隔符* /} textarea {width:100%;}

 < textarea id =post-textclass =form-controlrows =8placeholder =What's up? (晚上8点 - 晚上11点)周日练习@(9pm  -  12 am)< / textarea>< br>< br><输入类型= buttonid =post-buttonvalue =Post!>< div id =card-stack>< / div>  






如果您真的想在不使用的情况下使用CSS white-space 属性执行此操作,则另一种解决方案是显式替换文本中的任何换行符与< br> HTML标签。棘手的部分是,为避免引入细微的错误和潜在的安全漏洞,您必须首先转义任何HTML元字符(至少& )在您之前的文本中进行替换。



可能是最简单和最安全的方法那就是让浏览器为你处理HTML转义,就像这样:
$ b

  var post = document.createElement('p'); 
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/ \\\
/ g,'< br> \\\
');

  document.getElementById('post-button')。addEventListener('click',function(){var post = document.createElement('p'); var postText = document.getElementById('post-text') .value; post.textContent = postText; post.innerHTML = post.innerHTML.replace(/ \\\
/ g,'< br> \\\
'); //< - 此修补程序LINE BREAKS var卡= document.createElement('div'); card.appendChild(post); var cardStack = document.getElementById('card-stack'); cardStack.insertBefore(card,cardStack.firstChild);});

%;}

< tex tarea id =post-textclass =form-controlrows =8placeholder =What's up? (晚上8点 - 晚上11点)周日练习@(9pm - 12 am)< / textarea>< br>< br><输入类型= buttonid =post-buttonvalue =Post!>< div id =card-stack>< / div>

<请注意,虽然这将修复换行符,但它不会阻止HTML呈现器折叠连续的空格。有可能(有点)通过用不间断空格替换文本中的一些空白来模拟,但老实说,对于可以用一行CSS简单解决的事情来说,这变得相当复杂。


I am getting the value in a textarea when the user hits submit. I then take this value and place it elsewhere on the page. However, when I do this, it loses newline characters making the output pretty ugly.

Here is the textarea I am accessing:

<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required></textarea>

Here is the JavaScript code accessing the post and transcribing it.

var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.append(postText);
var card = document.createElement('div');
card.append(post);
var cardStack = document.getElementById('#card-stack');
cardStack.prepend(card);

When the input is something like:

Group Schedule:

Tuesday practice @ 5th floor (8 pm - 11 pm)

Thursday practice @ 5th floor (8 pm - 11 pm)

Sunday practice @ (9 pm - 12 am)

The output is:

Group Schedule: Tuesday practice @ 5th floor (8 pm - 11 pm) Thursday practice @ 5th floor (8 pm - 11 pm) Sunday practice @ (9 pm - 12 am)

So is there a way to preserve line breaks?

解决方案

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

document.getElementById('post-button').addEventListener('click', function () {
  var post = document.createElement('p');
  var postText = document.getElementById('post-text').value;
  post.append(postText);
  var card = document.createElement('div');
  card.append(post);
  var cardStack = document.getElementById('card-stack');
  cardStack.prepend(card);
});

#card-stack p {
  background: #ddd;
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
  width: 100%;
}

<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="card-stack"></div>


Note that, like your original code, the snippet above uses append() and prepend(). As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:

  • element.append(otherElement) can be replaced with element.appendChild(otherElement);
  • element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);
  • element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));
  • element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);
  • as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.

Here's the same snippet as above, but without using append() or prepend():

document.getElementById('post-button').addEventListener('click', function () {
  var post = document.createElement('p');
  var postText = document.getElementById('post-text').value;
  post.textContent = postText;
  var card = document.createElement('div');
  card.appendChild(post);
  var cardStack = document.getElementById('card-stack');
  cardStack.insertBefore(card, cardStack.firstChild);
});

#card-stack p {
  background: #ddd;
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
  width: 100%;
}

<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="card-stack"></div>


Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with <br> HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.

Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:

var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');

document.getElementById('post-button').addEventListener('click', function () {
  var post = document.createElement('p');
  var postText = document.getElementById('post-text').value;
  post.textContent = postText;
  post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');  // <-- THIS FIXES THE LINE BREAKS
  var card = document.createElement('div');
  card.appendChild(post);
  var cardStack = document.getElementById('card-stack');
  cardStack.insertBefore(card, cardStack.firstChild);
});

#card-stack p {
  background: #ddd;
}
textarea {
  width: 100%;
}

<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="card-stack"></div>

Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.

这篇关于从textarea获取文本时如何保留换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆