Bashar Hamed
Bashar Hamed

Reputation: 23

How do I split a sentence to an array of sentences with maximum number of characters without cutting words?

I have this string:

This is a sentence to be split by the code, how can I make it smaller with maximum number of 30 characters?

And I want to make it into this array in Javascript:

[
"This is a sentence to be split",
"by the code, how can I make",
"it smaller with maximum",
"number of 30 characters?"
]

How can I split that string, using Javascript, with maximum lenght of 30 characters per each sentence split, and with whole words?

I found this code:

How do I split a string at a space after a certain number of characters in javascript?

That did a great job, but it found the space after the 30 characters limit, not before it:

function myFunction() {
    str = "This is a sentence to be split by the code, how can I make it smaller with maximum number of 30 characters?"
    result = str.replace(/.{30}\S*\s+/g, "$&@")
    document.getElementById("demo").innerHTML = result;
}

Upvotes: 1

Views: 302

Answers (1)

Toto
Toto

Reputation: 91385

In order to avoid a space at the beginning or at the end of each part, use:

var str = "This is a sentence to be split by the code, how can I make it smaller with maximum number of 30 characters?";
console.log(str.match(/\S.{0,29}(?=\s+|$)/g));

Upvotes: 1

Related Questions