Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove Space From Start and End From All Lines of TextArea

What I am looking for remove white space from every line start and end. I am trying the code posted on this answer

var lines = $("textarea[name=f01]") .val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
  if (/\S/.test(lines[i])) {
    texts.push($.trim(lines[i]));
  }
}
var n = texts.toString().split(",").join("\n");
$("textarea[name=f01]") .val(n);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea name="f01" id="40459045A">
 आज शिद्दत से 
दिल चाह रहा है,            
बंद आँखें खोलूं तो 
सामने तुम हो !!
</textarea>

But result is like this

Result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think when , at the line end, its creating new empty line in it. I want result like

आज शिद्दत से
दिल चाह रहा है,
बंद आँखें खोलूं तो
सामने तुम हो !!

Let me know what I am missing in this. Thanks!

>Solution :

The code you copied assumes that the text will not contain ,. Converting an array to a string is equivalent to array.join(','). Then it’s splitting that with .split(',') to get the array elements. Buf if any of the strings contain a comma, this will split it into two lines in the result.

Just use texts.join('\n'). I have no idea why the other answer uses that.

var lines = $("textarea[name=f01]") .val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
  if (/\S/.test(lines[i])) {
    texts.push($.trim(lines[i]));
  }
}
var n = texts.join("\n");
$("textarea[name=f01]") .val(n);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea name="f01" id="40459045A">
 आज शिद्दत से 
दिल चाह रहा है,            
बंद आँखें खोलूं तो 
सामने तुम हो !!
</textarea>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading