You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中为API返回的表格数据重新应用掩码(CRUD场景)

解决表格中CNPJ重新添加掩码的问题

嘿,这个场景太常见了!表单提交时用掩码提升用户体验,传给后端用纯数字保证数据一致性,现在要在表格展示时还原掩码,只需要加个格式化函数就行,我给你一步步说:

1. 写一个CNPJ掩码格式化函数

首先创建一个专门处理CNPJ格式的函数,接收纯数字的CNPJ字符串/数字,返回带标准掩码的格式:

function formatCNPJ(cnpj) {
  // 先把输入转为字符串,并移除所有非数字字符(保险起见,防止API返回意外格式)
  const cleanCNPJ = cnpj.toString().replace(/\D/g, '');
  
  // 用正则表达式匹配并添加CNPJ标准掩码
  return cleanCNPJ.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5');
}

这个函数会把纯数字的12345678000195转换成符合规范的12.345.678/0001-95。

2. 修改表格渲染代码

接下来在你的exibirEmpresas函数里,把原本直接输出lista.cnpj的地方,换成调用这个格式化函数就行。另外我还帮你修复了dadosEmpresa变量重复累积的问题:

let dadosEmpresa = ''; // 初始化变量

const exibirEmpresas = (u) => {
  dadosEmpresa = ''; // 每次渲染前清空,避免多次调用时数据重复
  Array.from(u).forEach((lista) => {
    dadosEmpresa += ` 
    <tr>
      <td class="idEmp" id="idEmp">${lista.idEmpresa}</td>
      <td class="nomeEmp">${lista.nomeEmpresa}</td>
      <td class="emailCad">${lista.email}</td>
      <td class="cnpjCad" id="cnpjList">${formatCNPJ(lista.cnpj)}</td> <!-- 这里调用格式化函数 -->
      <td class="dataCadastroCad">${lista.dataCadastro}</td>
      <td class="dataAtualizacaoCad">${lista.dataAtualizacao}</td>
      <td>
        <button id="atualiza-empresa" onclick="editItem(${lista.idEmpresa})">Editar</button>
      </td>
      <td>
        <button class="deletebtn" onclick="removeItem(${lista.idEmpresa})">Excluir</button>
      </td>
    </tr>
    `;
  });
  listaEmpresa.innerHTML = dadosEmpresa;
};

// GET 请求部分保持不变
fetch(urlAPI)
 .then((s) => s.json())
 .then((dados) => exibirEmpresas(dados));

额外小提示

  • 如果API返回的CNPJ可能存在长度不足14位的情况,可以在格式化函数里加个校验逻辑,比如:
    if (cleanCNPJ.length !== 14) return cnpj; // 不符合长度则返回原数据
    
  • 要是以后需要格式化其他字段(比如CPF、手机号),可以用同样的思路写对应的格式化函数,复用性拉满。

内容的提问来源于stack exchange,提问作者Lucas Marins Pinheiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:19:26