Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Created January 25, 2022 11:08
Show Gist options
  • Save wojtekmaj/53934ff72f7d8e1c83986f723c39f7de to your computer and use it in GitHub Desktop.
Save wojtekmaj/53934ff72f7d8e1c83986f723c39f7de to your computer and use it in GitHub Desktop.
Add word breaks to text in React
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