使用jQuery修剪textarea中的前导/后缀空白吗?

问题描述:

以下代码是将文本从数据库放入文本区域的示例.

Following code is an example of text placed into a textarea from a database.

<textarea id="inputPane" cols="80" rows="40" class="pane">
<p>
    some text here...
</p>
  <p>
    more text here...
</p>
</textarea>

使用jQuery的.trim,实际的jquery代码是什么,以删除所有前导和尾随空格,并使textarea显示与下面非常相似?

using jQuery's .trim what is the actual jquery code to remove all leading and trailing whitespace and have the textarea display very similar to below?

<textarea id="inputPane" cols="80" rows="40" class="pane">
    <p>some text here...</p>
    <p>more text here...</p>
</textarea>

我已经尝试了数小时,但尝试使用.trim进行各种组合却没有成功

I've worked on this for hours with no success trying varying combinations with .trim

$('#inputPane')jQuery.trim(string);

您可以尝试以下方法:

jQuery(function(​$) {
    var pane = $('#inputPane');
    pane.val($.trim(pane.val()).replace(/\s*[\r\n]+\s*/g, '\n')
                               .replace(/(<[^\/][^>]*>)\s*/g, '$1')
                               .replace(/\s*(<\/[^>]+>)/g, '$1'));
});​

哪个给出结果:

<p>some text here...</p>
<p>more text here...</p>

尽管这可能不是防弹的,但它应该比从textarea的HTML值创建元素要快得多/高效.

Though this may not be bulletproof, it should prove to be much faster/more efficient than creating elements from the HTML value of the textarea.