如何在copy事件监听中移除DOM元素所有属性及多余空白字符?
移除复制内容中的DOM属性与多余空白字符
我实现了一个监听copy事件的事件监听器,希望从复制的数据中移除DOM元素的所有属性,同时清除代码中的多余空白字符。相关代码及预期效果如下:
当前代码
document.addEventListener("copy", function(event) { let target = event.target, selectedText = ''; if (target.nodeName === "INPUT" || target.nodeName === "TEXTAREA") {selectedText = target.value.substring(target.selectionStart, target.selectionEnd);} else{ const selection = window.getSelection(); if (selection.rangeCount > 0) { const range = selection.getRangeAt(0); const clonedSelection = range.cloneContents(); const tempDiv = document.createElement('div'); tempDiv.appendChild(clonedSelection); selectedText = tempDiv.innerHTML; } } selectedText = selectedText.replace(/(class|id|style|data-*|src|alt)\s*=\s*"[^"]*"/g, ''); // 需要修改此处 selectedText = selectedText.trim(); console.log (selectedText.length); console.log (selectedText); if (selectedText.length > 0){ chrome.runtime.sendMessage({type: "copy-event",data: selectedText}); } });
示例HTML代码
<section class="box_section mobile-collapse" data-nid="2279" data-cms-title="What is ASD? " data-cms-anchor="1"> <h2 id="part_2279">What is ASD? </h2> <div> <p>Autism spectrum disorder (ASD) is a neurological and developmental disorder that affects how people interact with others, communicate, learn, and behave. Although autism can be diagnosed at any age, it is described as a “developmental disorder” because symptoms generally appear in the first 2 years of life.</p> <p>According to the <em>Diagnostic and Statistical Manual of Mental Disorders (DSM-5)</em>, a guide created by the American Psychiatric Association that health care providers use to diagnose mental disorders, people with ASD often have:</p> <ul><li>Difficulty with communication and interaction with other people</li> <li>Restricted interests and repetitive behaviors</li> <li>Symptoms that affect their ability to function in school, work, and other areas of life</li> </ul><p>Autism is known as a “spectrum” disorder because there is wide variation in the type and severity of symptoms people experience.</p> </div> </section>
期望结果
<section><h2>What is ASD? </h2><div> <p>Autism spectrum disorder (ASD) is a neurological and developmental disorder that affects how people interact with others, communicate, learn, and behave. Although autism can be diagnosed at any age, it is described as a “developmental disorder” because symptoms generally appear in the first 2 years of life.</p><p>According to the <em>Diagnostic and Statistical Manual of Mental Disorders (DSM-5)</em>, a guide created by the American Psychiatric Association that health care providers use to diagnose mental disorders, people with ASD often have:</p> <ul><li>Difficulty with communication and interaction with other people</li> <li>Restricted interests and repetitive behaviors</li> <li>Symptoms that affect their ability to function in school, work, and other areas of life</li> </ul><p>Autism is known as a “spectrum” disorder because there is wide variation in the type and severity of symptoms people experience.</p></div></section>
优化后的代码
document.addEventListener("copy", function(event) { let target = event.target, selectedText = ''; if (target.nodeName === "INPUT" || target.nodeName === "TEXTAREA") { selectedText = target.value.substring(target.selectionStart, target.selectionEnd); } else { const selection = window.getSelection(); if (selection.rangeCount > 0) { const range = selection.getRangeAt(0); const clonedSelection = range.cloneContents(); const tempDiv = document.createElement('div'); tempDiv.appendChild(clonedSelection); selectedText = tempDiv.innerHTML; } } // 1. 移除所有DOM属性 selectedText = selectedText.replace(/\s+[a-zA-Z0-9-]+="[^"]*"/g, ''); // 2. 清除标签间的多余空白和换行,保留列表项内的换行 selectedText = selectedText .replace(/>\s+</g, '><') // 移除标签之间的所有空白 .replace(/<li>\s+/g, '<li>') // 移除<li>后的多余空格 .replace(/\s+<\/li>/g, '</li>') // 移除</li>前的多余空格 .replace(/<ul>\s+/g, '<ul>') // 移除<ul>后的多余换行 .replace(/\s+<\/ul>/g, '</ul>') // 移除</ul>前的多余换行 .trim(); console.log(selectedText.length); console.log(selectedText); if (selectedText.length > 0){ chrome.runtime.sendMessage({type: "copy-event", data: selectedText}); } });
修改说明
- 移除所有属性:将原正则替换为
/\s+[a-zA-Z0-9-]+="[^"]*"/g,该正则能匹配所有以字母、数字、连字符组成的属性名,彻底移除所有元素属性,无需逐个指定。 - 清理空白字符:通过多步正则替换,先合并标签间的空白(比如
> <变为><),再单独处理列表项前后的多余空格,既清除了冗余空白,又保留了列表项的换行结构,符合期望结果的格式。
内容的提问来源于stack exchange,提问作者3 Popcorns
相关产品推荐
相关产品推荐

