-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplitIntoLines.tsx
44 lines (38 loc) · 1.08 KB
/
splitIntoLines.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import React, { Fragment } from 'react';
/**
* Разбивает переданный текст на строки.
* @param {string} text Текст с символами разделения
* @param {string} divider Символ разделения, по умолчанию \n
* @param {boolean} lineBreak Добавить переносы строк, по умолчанию true
* @returns {JSX.Element} React.Fragment, содержащий span-элементы с текстом строк
*/
export default (
text: string,
divider: string | RegExp = '\n',
lineBreak = true
): JSX.Element => {
if (text.length === 0) {
return <Fragment />;
}
const lines = text.split(divider);
if (lineBreak) {
const lastIndex = lines.length - 1;
return (
<>
{lines.map((line, index) => (
<Fragment key={index}>
{line}
{index !== lastIndex && <br />}
</Fragment>
))}
</>
);
}
return (
<>
{lines.map((line, index) => (
<span key={index}>{line}</span>
))}
</>
);
};