0

I am trying to figure out if there is a way for either angular or just pure javascript to get the value of a textarea's row?

I have a project that I am working on with a fixed size textarea, once it reaches a certain number of characters, it needs to wrap to a new row (not necessarily a line break). In my project I need to post each row of text as if it was a new object to the server. So for example, if a person types a really long sentence, whatever word(s) exceeds the character limit needs to wrap into a new row. I then need to post the data back to the server as if each displayed row was a new object

This what I started to create, but realized it would not work for my needs, as a long sentence or paragraph may not have a line break, and each row is not exactly the same length in characters because a long word could wrap into a new row

 Test(textarea) {
   console.log(textarea)
   let data = [];
   console.log(this.test)
   data = this.test.split('\n');
   data.forEach(element = > {
     var item = {
       text: element
     }
     console.log(item)
   });
 }
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
Tom Yee
  • 69
  • 6
  • A ` – David Thomas Dec 10 '18 at 21:26
  • Keep in mind... you can't really trust at what point the textarea wraps either... the user can zoom in the text, resize the textarea, etc.. Ultimately you'll just have to decide on a max line length and then split the content up accordingly... which actually makes the solution a bit simpler due to not having to deal with messing with the textarea. – Kevin B Dec 10 '18 at 22:09

1 Answers1

0

You need to do a bit of parsing to satisfy the requirements - this is what I came up with:

const maxLength = 20;

const splitToLength = sentence => {
  if (sentence.length <= maxLength) {
      return [sentence];
  }
  const index = sentence.lastIndexOf(' ', maxLength);
  return [
    sentence.substr(0, index), 
    splitToLength(sentence.substr(index +1))
  ].flat();
}

const input = 'Lorem ipsum dolor amet kombucha health goth put a bird on it, kogi photo booth hella whatever butcher.\nSingle-origin coffee food truck thundercats small batch banh mi franzen blog snackwave deep v plaid narwhal vaporware. Cold-pressed snackwave bitters cardigan, palo santo chillwave wayfarers street art tote bag flexitarian selvage four loko. Next level affogato vice poutine brooklyn sustainable raw denim normcore post-ironic williamsburg.\nReadymade butcher meh, subway tile bushwick biodiesel helvetica cred ethical mixtape meditation plaid. Ugh banjo snackwave street art coloring book iceland lomo mlkshk DIY vape edison bulb. Copper mug salvia sustainable next level artisan coloring book ugh distillery schlitz listicle food truck etsy offal adaptogen iceland.'

const output = input
  .split('\n')
  .map(splitToLength)
  .flat()
  .map(text => ({text}));
 
 console.log(output);
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53