Splitting a long string into two parts, without breaking up words

While building websites, I always try to set things up as efficiently as possible, and so today I had a long string that would have to be shown in two separate columns on desktop.

Manon Heine
2 min readDec 28, 2023

As it turns out, there are several ways of doing this: you could split it in your backend and give your frontend two separate strings, you can split it with Javascript, or you can use a nifty little CSS trick for this.

Two columns consisting of one string

We won’t cover the backend here, let’s stay away from the Dark Side for now. Let’s start with the Javascript code for this:

const { string1, string2 } = this.splitText(str);

splitText(str: string) {
const l = str.length;
const string1 = str.substring(0, str.indexOf(' ') + l / 2);
const string2 = str.substring(str.indexOf(' ') + l / 2).trimStart());
return { string1, string2 };
}

What we do here, is that we use substring() to split the original string in two pieces by checking if we have reached half of the length of the string at a space (that’s what the indexOf(' ') is for. trimStart() is used to remove the space at the start of the second string.

This works fine if you need these strings in your Javascript code or if you want full control over how much text you want in each column, e.g. if you would want 2/3 of the text in the first column and 1/3 in the second.

However, there is a faster way to achieve the same result if you just want a simple split, by using CSS:

// in your template
<div class="split">{{ text }}</div>

// in your styles
.split {
column-count: 2;
}

column-count is a relatively new feature but very useful if you want to distribute your content in several columns. For more info, check out the MDN docs. You can further style your columns with column-gap, column-rule and column-span.

Hope this helped you in finding the appropriate solution for splitting your strings or distributing objects across columns. Let me know in a comment or with a clap if this was useful to you.

Happy coding!

--

--

Manon Heine

Frontend dev, passionate about UI/UX design and psychology. Mountain maniac, powder lover & rider.