Trim leading/trailing whitespace from textarea using jQuery?

caroline picture caroline · Sep 15, 2010 · Viewed 21.8k times · Source

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>

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>

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

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

Answer

Kevin picture Kevin · Sep 15, 2010

You could try something like this:

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'));
});​

Which gives the result:

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

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.