当前位置: 首页 > news >正文

vue3 处理文字 根据文字单独添加class

下面写的是根据后端返回的html 提取我需要的标签和字 将他们单独添加样式

后端返回的数据 大概类似于'<h1>2024年“双11”购物节网络零售监测报告</h1><p>表1 “双11” 期间网络零售热销品类TOP10</p>'

function checkfun(newList){
    if (newList) {
        let processedAnswer = newList
         // 这个是判断如果是h2标签里面只有前言这两字的时候就添加class
        .replace(    
            /<h2>(前言)<\/h2>/gs, 
            '<h2><span class="titleclass">$1</span></h2>'
        // 这个是判断如果是h2标签里面只有报告说明这两字的时候就添加class
        ).replace(
            /<h2>(报告说明)<\/h2>/gs,
            '<h2><span class="titleclass">$1</span></h2>'
        // 这个是判断如果是如果包含表1,图1等的时候就添加class
        ).replace(
            /((?:表|图)\d+.*?)(?=(?:<p>|<\/p>|<h2>|<h3>|<li>|<\/li>|$))/gs,
            '<span class="picture">$1</span>'
        )
        // 这个是判断如果是如果注的时候就添加class
        .replace(
            /((?:注)\d+.*?)(?=(?:<p>|<\/p>|<h2>|<h3>|<li>|<\/li>|$))/gs,
            '<span class="pour">$1</span>'
        )

        // 添加表格处理逻辑  --- 这个是我根据标准的table格式进行添加class
        const doc = parseHTML(processedAnswer);
        const tables = doc.querySelectorAll('table');
        tables.forEach((table) => {
            // 判断是否是table是否只有一个表头
            const thead = table.querySelector('thead');
            const theadLength = thead?.rows[0]?.cells.length || 0;
            if (theadLength === 1) {
                table.classList.add('single-header');
            }
            // 判断表身里面的数据 是否是数字
            const tbody = table.querySelector('tbody');
            tbody?.querySelectorAll('td').forEach((td) => {
                if (isStringNumber(td.textContent)) {
                    td.classList.add('single-cell');
                }
            });

            // 检查表头是否包含“排名”字段  -- 并且排名这个字段必须在第一位
            const headers = table.querySelectorAll('thead th:first-child');  
            const rankIndex = Array.from(headers).findIndex(header => header.textContent.trim() == '排名');  
            // 如果找到排名列,为所有对应单元格添加样式
            if (rankIndex !== -1) {
                // 获取所有行数据
                const rows = table.querySelectorAll('tbody tr');
                
                rows.forEach(row => {
                    const cells = row.querySelectorAll('td');
                    if (cells.length > rankIndex) {
                        cells[rankIndex].classList.add('rank-column');
                    }
                });
            }
        });
        
        // 获取到所有的p标签和li标签 判断里面是否有数字和英文 如果有的话将他们单独添加class
        const pElements = doc.querySelectorAll('p, li');
        pElements.forEach(p => {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = p.innerHTML;
            
            const walker = document.createTreeWalker(tempDiv, NodeFilter.SHOW_TEXT);
            
            let node;
            while ((node = walker.nextNode())) {
                const parent = node.parentNode;
                const text = node.textContent;
                let lastIndex = 0;
            
                // 改进后的正则表达式
                const numberRegex = /(-?\d+(?:\.\d+)?|[a-zA-Z']+)/g;
            
                let numberMatch;
                while ((numberMatch = numberRegex.exec(text)) !== null) {
                    const span = document.createElement('span');
                    span.className = 'english-style';
                    span.textContent = numberMatch[0];
                    
                    const textBefore = document.createTextNode(text.slice(lastIndex, numberMatch.index));
                    parent.insertBefore(textBefore, node);
                    parent.insertBefore(span, node);
                    
                    lastIndex = numberRegex.lastIndex;
                }

                // 添加剩余文本
                if (lastIndex < text.length) {
                    const remainingText = document.createTextNode(text.slice(lastIndex));
                    parent.insertBefore(remainingText, node);
                }
                parent.removeChild(node);
            }
            p.innerHTML = tempDiv.innerHTML;
        });

        // 将处理后的DOM转换回HTML字符串
        processedAnswer = serializeHTML(doc.body);

        processedList.value = processedAnswer
    }
}
const isStringNumber = (str) => {
    // 匹配整数、小数、负数
    const numberRegex = /^[-+]?(?:\d{1,3}(?:,\d{3})*(?:\.\d+)?|\d+(?:\.\d*)?|\.\d+)$/;
    return numberRegex.test(str);
};
// 转化为html
function parseHTML(htmlString) {
  const parser = new DOMParser();
  return parser.parseFromString(htmlString, 'text/html');
}
// 添加HTML序列化工具函数
function serializeHTML(node) {
  const temp = document.createElement('div');
  temp.appendChild(node.cloneNode(true));
  return temp.innerHTML;
}

px,pt,em换算表 | 菜鸟教程https://www.runoob.com/w3cnote/px-pt-em-convert-table.html像素与磅换算 -- EndMemohttps://endmemo.com/topography/pixelpointcn.html

相关文章:

  • MySQL基础 [五] - 表的增删查改
  • 进程状态(运行 阻塞 僵尸)及其场景分析
  • 智谛达多功能人形机器人:未来生活的得力助手
  • DMA 概念与讲解
  • LeetCode 热题 100_完全平方数(84_279_中等_C++)(动态规划(完全背包))
  • 随机产生4位随机码(java)
  • 设计模式之享元模式
  • 图解AUTOSAR_SWS_FlexRayDriver
  • 使用分布式锁和乐观锁解决超卖问题
  • 闪蒸高密度聚乙烯无纺布市场报告:探索高性能材料的新机遇
  • 搜广推面经六十八
  • yum拒绝连接
  • 【区块链+ 人才服务】蓝鲸智课——区块链课程与实训平台 | FISCO BCOS 应用案例
  • GS069W电动工具直流调速电路:高效调速方案解析
  • 【多线程-第四天-自己模拟SDWebImage的下载图片功能-取消操作 Objective-C语言】
  • Quartz 分布式集群 数据持久化任务调度系统
  • 【VScode】C/C++使用教程
  • C++11实现一个自旋锁
  • Flutter:Flutter SDK版本控制,fvm安装使用
  • 寄存器相关及清零、置1、取反等位移操作
  • 网站开发工作怎样/推广工作的流程及内容
  • 邢台网站建设报价/线上推广策划方案
  • 怎么让别人看到自己做的网站/网络推广预算方案
  • 前几年做那个网站能致富/引流黑科技app
  • 个人网站怎么申请注册/徐州网站设计
  • 沂南网站建设/徐州百度推广总代理