Files
vf_react/src/utils/textUtils.js
2025-10-11 12:02:01 +08:00

76 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 文本处理工具函数
*/
/**
* 处理包含<br>标签的文本转换为适合在React中显示的格式
* @param {string} text - 包含<br>标签的文本
* @param {string} mode - 处理模式:'html' 使用dangerouslySetInnerHTML, 'text' 转换为纯文本换行, 'remove' 直接去掉br标签
* @returns {string} 处理后的文本
*/
export const formatTextWithBr = (text, mode = 'text') => {
if (!text) return '';
switch (mode) {
case 'html':
// 用于dangerouslySetInnerHTML保持换行效果
return text
.replace(/<br\s*\/?>(\s*)/g, '\n') // 将br标签转换为换行符
.replace(/\n{2,}/g, '\n') // 去掉多余的换行符
.replace(/\n/g, '<br/>'); // 重新转换为br标签
case 'text':
// 用于普通Text组件配合whiteSpace="pre-line"使用
return text
.replace(/<br\s*\/?>(\s*)/g, '\n') // 将br标签转换为换行符
.replace(/\n{2,}/g, '\n') // 去掉多余的换行符
.trim();
case 'remove':
// 直接去掉br标签用空格替代
return text
.replace(/<br\s*\/?>(\s*)/g, ' ') // 将br标签替换为空格
.replace(/\s{2,}/g, ' ') // 去掉多余的空格
.trim();
default:
return text;
}
};
/**
* 为文本添加样式化的换行处理
* @param {string} text - 原始文本
* @returns {object} 包含处理后文本和样式的对象
*/
export const getFormattedTextProps = (text) => {
if (!text) return { children: '', props: {} };
const formattedText = formatTextWithBr(text, 'text');
return {
children: formattedText,
props: {
whiteSpace: 'pre-line',
lineHeight: '1.6',
wordBreak: 'break-word'
}
};
};
/**
* 为工具提示(Tooltip)优化的文本格式化
* @param {string} text - 原始文本
* @param {number} maxLength - 最大长度,超出部分用...省略
* @returns {string} 处理后的文本
*/
export const formatTooltipText = (text, maxLength = 200) => {
if (!text) return '';
const cleaned = formatTextWithBr(text, 'text');
if (cleaned.length <= maxLength) return cleaned;
return cleaned.substring(0, maxLength) + '...';
};