#Dividing a String Across Lines

12 messages · Page 1 of 1 (latest)

twilit marten
#

I have a string and I want to divide it into an array of strings that will be put on separate lines, where each string (or line) is not more than a given length. Each string should only be split on characters that normally allow line breaks, such as spaces.

For example, "Hello World" with a maxLength of 5 would be split into ["hello", "world"]. "Reference site about Lorem Ipsum" with a maxLength of 14 would be split into ["Reference site", "about Lorem", "Ipsum"].

Is there a built-in function to do this?

tame riverBOT
#

This post has been reserved for your question.

Hey @twilit marten! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

icy rampart
#

There is String#split

twilit marten
#

Doesn't that split on specific characters?

icy rampart
#

yes it does. You can use a regex pattern and it will split the provided string at each match

twilit marten
#

I only want it to split on line-breaking characters like spaces once it has exceeded the maximum line limit, though...

So
not
this

#

Is there a way to make String#split do that?

icy rampart
#

you can split the String using String#split and then append the substrings that are under your character limit. Alternatively use a for-loop.

twilit marten
#

Ok... I suppose I could just code it up myself, but if there's a built-in implementation, I can almost guarantee it'll be better than anything I write. Sounds like there isn't really one, though.

icy rampart
#

No that I am aware of.

twilit marten
#

Ok.