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

如何用正则表达式扫描网页提取值并忽略表单字段?

忽略表单字段的正则匹配方案

要解决匹配到textarea和文本类input内内容的问题,只需在过滤文本节点时,新增对表单元素的检查,排除掉这些区域内的文本节点即可。

修改后的完整代码

const regex = /\s*(([+]?(\s?\d)([-\s]?\d)|0)?(\s?\d)([-\s]?\d){9}|[(](\s?\d)([-\s]?\d)+\s*[)]([-\s]?\d)+)\s*/;

function handleTextNode(textNode) {
    if(textNode.parentElement) {
        textNode.parentElement.innerHTML = textNode.parentElement.innerHTML.replace(regex, function(match){
            return `<i class="fa fa-phone-square" style="color:#e52420;"></i> <a href="javascript:void(0);" class="c2d_phonenumber" style="background:#e52420; color:#ffffff">${match}</a>`;
        });
    }
}

function textNodesUnder(el) {
    var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
    while(n=walk.nextNode()) a.push(n);
    return a;
}

function processDocument() {
    let nodeList = textNodesUnder(document.body);
    nodeList = nodeList.filter(node => regex.test(node.nodeValue))
                       .filter(textNode => {
                           // 排除script、style,以及表单字段内的文本节点
                           const isForbiddenParent = textNode.parentNode.nodeName === "SCRIPT" || textNode.parentNode.nodeName === "STYLE";
                           const isInFormField = textNode.parentElement?.closest('textarea, input[type="text"], input[type="tel"], input[type="email"], input[type="password"]');
                           return textNode.nodeName === "#text" && !isForbiddenParent && !isInFormField;
                       });
    
    nodeList.forEach(function (el) {
        handleTextNode(el);
    });
}

关键修改说明

  • 在第二个filter中新增了isInFormField判断:通过closest方法检查当前文本节点的祖先元素中是否存在textarea或文本类input(包括text、tel、email、password类型),如果存在则排除该文本节点。
  • 把原有的分散过滤条件整合到一个filter回调里,代码逻辑更紧凑。

修改后,正则匹配会自动忽略textarea和各类文本输入框内的内容,仅处理页面正常文本区域的匹配。

内容的提问来源于stack exchange,提问作者charlie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:05:07