Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit line breaks in textarea

I have a text area, where i want to allow users to make line break by pressing enter, but i want to limit that to only one break, because then the users could add as many breaks they want, creating huge white space in the output.

  <textarea maxLength={3000} onChange={(e) => setPersonBio(e.target.value)} value={personBio} type="text" rows="5" className="bio-content" placeholder="Enter something about yourself..."></textarea>

And then i display it in <p> tag with white-space: pre-line;

My question is how to limit the amount of breaks user can enter, or delete the additional ones after submitting.

like image 252
tomasborek Avatar asked Nov 15 '25 14:11

tomasborek


1 Answers

You can use the String methods search and include inside a while loop to remove all but one of a given repeated character.

text = "abc\n\n\ndef\n\nghi"; 
document.write('<textarea rows=6>'+text+'</textarea>');
while (text.includes("\n\n"))
  text = text.replace("\n\n","\n");
document.write('<textarea rows=6>'+text+'</textarea>');
like image 144
JMP Avatar answered Nov 18 '25 04:11

JMP