Ad

Force Line Break After First Word In A Div In React Component

I am working with a <div> where data comes as simple text from an outer source. For instance <div>Business in three different continents.</div> . Now I need to show this text like below:

         Business

in four different countries

Must have:text-align: center; and line break always after the first word only.

Problem Since I have only one HTMLelement as in <div> to work with I can not add \n inside the <div> content. This would only either be after or before the entire line of text if I use pseudo element &::before / &::after (for the @emotion/styled I am using) and not after the first word. Since CSS can't count words it seems this issue can not be solved with CSS only. Also the <div> container width has to adjust to the second line, hence I can't use display:block because it will be applied to the entire line of text. Saw in other posts to add two white spaces to force line break but this can't be done just after first word since I don't have any nested HTMLelement, like <div><span></span></div>

Btw, can react-markdown help?

What is the best way to solve this problem?

Ad

Answer

Why not use JS to break the string into two parts?

var sentence = "Business in three different continents.";
var firstWhiteSpace = sentence.indexOf(" ");
var firstWord = sentence.substr(0, firstWhiteSpace);
var restOfSentence = sentence.substr(firstWhiteSpace+1);

// Then you can use different divs for the first word and the rest of the 
// sentence and style then individually.
<div>firstWord</div>
<div>restOfSentence</div>
Ad
source: stackoverflow.com
Ad