1

Using jQuery, I have a situation where I need to remove all trailing whitespaces within a textarea field on a per line basis.

For example, I have the following case:

<textarea name="f01" rows="30" cols="90" wrap="VIRTUAL" id="40459045A">
CC9G-ws-001       
9G-ws-001       
G-AAG-001     
REE65M         
NONE4007M    
GE4M            
GLBNE2101           
7SK-E-902     
EM-E-902   
</textarea>

I am referencing the textarea in jQuery using $("textarea[name=f01]") but I am not sure how to remove the trailing spaces for each line.

If you highlight one of the rows within the above textarea tags, you will see the trailing spaces. I would like all of those removed.

Additionally, I would like the actual result of all the trailing spaces removed for each of the textarea lines returned to one value result, as I need to then use this result for some other processing.

halfer
  • 19,824
  • 17
  • 99
  • 186
tonyf
  • 34,479
  • 49
  • 157
  • 246
  • have a look on this: http://stackoverflow.com/questions/3721999/trim-leading-trailing-whitespace-from-textarea-using-jquery – Tal Levi Aug 14 '14 at 08:20
  • @TalLevi tried this one but receive some illegal character problems. If possible, could a jsFiddle be setup to demonstrate for my situation, just in case I've missed something. Thanks. – tonyf Aug 14 '14 at 08:23

1 Answers1

2

Try this..

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);    

JsFiddle demo : http://jsfiddle.net/fu326pay/

RahulB
  • 2,070
  • 1
  • 18
  • 26
  • 1
    Perfect - just what I wanted and appreciate the jsfiddle demo. – tonyf Aug 14 '14 at 15:10
  • What's the reason for `texts.toString().split(",")`? Why not just join `texts`? – Barmar Jun 24 '22 at 00:34
  • Apple uses \r for their line break representation, wouldn't this fail for that OS? I don't have any apple device so I can't test. I think .split(/\r?\n/) would fix that. – tb. Feb 06 '23 at 15:45