Created
January 25, 2022 11:08
-
-
Save wojtekmaj/53934ff72f7d8e1c83986f723c39f7de to your computer and use it in GitHub Desktop.
Add word breaks to text in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pattern = /_/g; | |
function addWordBreaks(text) { | |
const splitText = text.split(pattern); | |
if (splitText.length <= 1) { | |
return text; | |
} | |
const matches = text.match(pattern); | |
return splitText.reduce( | |
(arr, element, index) => | |
matches[index] | |
? [ | |
...arr, | |
element, | |
matches[index], | |
<wbr key={index} />, | |
] | |
: [...arr, element], | |
[], | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment