简体   繁体   中英

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

结果

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!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM