0

I want to store 21 char in an array from a string. my problem is when I'm writing a paragraph it cuts the word like this.

    let string = "This is a new paragraphe that i'm writing to you" //  48 chars and 10 words
    let lines = string.match(/.{1,21}/g)
    console.log(lines) //  ["This is a new paragra", "phe that i'm writing ", "to you"]

I want it to look like this ["This is a new" , "paragraphe that i'm" , "writing to you"] and don't cut the word.

EyTa
  • 109
  • 3
  • 10

1 Answers1

2

Use the \b anchors to define word boundaries, and you are set:

let string = "This is a new paragraphe that i'm writing to you";

let lines = string
  .match(/\b.{1,21}\b/g)
  .map(line => line.trim());
  
console.log(lines);
31piy
  • 23,323
  • 6
  • 47
  • 67
  • when i'm trying something like this. string= "Le mot le plus long de la langue française Anti Consituionnellement" I get ["Le mot le plus long", "de la langue franç", "aise est", "Anti", "Consituionnellement"] it's in french and like you see it cut my word – EyTa May 07 '18 at 09:56
  • 1
    @EyTa -- please see [this post](https://stackoverflow.com/questions/2449779/why-cant-i-use-accented-characters-next-to-a-word-boundary). This is a limitation of JavaScript. – 31piy May 07 '18 at 10:03