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);
Get the value, trim the value, set the value:
Or in one line:
You don't need jQuery to Trim leading/trailing whitespace from textarea. You need to code it in 1 line
Before:
After:
This is how I would do it (demo):
jQuery.trim()
will remove leading and trailing whitespace from the entire string -- in this case, before the first<p>
and after the last</p>
. You want something more complex, which is to remove whitespace between certain tags. This is not necessarily easy, but could (perhaps!) be accomplished with a regular expression, for example:DISCLAIMER: This was just quickly put together and may not cover every case.
You could try something like this:
Which gives the result:
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.
Try this:
It turns the content of the
textarea
into elements, walks through them and trims the content, then inserts the resulting HTML back into thetextarea
.EDIT: Modified to use
.val()
instead of.text()
as noted by @bobince