Estoy creando una extensión de Chrome que debe repetir todas las palabras en una página web y reemplazarlas con imágenes. El problema es que no puedo entender correctamente todas las palabras. Este es el código que tengo hasta ahora. Estoy ejecutando esto en content.js.
walk(document.body, /([^\s]+)/g); function walk(node, targetRe) { var child; switch (node.nodeType) { case 1: // Element for (child = node.firstChild; child; child = child.nextSibling) { walk(child, targetRe); } break; case 3: // Text node handleText(node, targetRe); break; } } function handleText(node, targetRe) { var match, targetNode, followingNode, wrapper; // Does the text contain our target string? // (This would be a regex test in your http://... case) match = targetRe.exec(node.nodeValue); if (match) { // Split at the beginning of the match targetNode = node.splitText(match.index); // Split at the end of the match. // match[0] is the full text that was matched. followingNode = targetNode.splitText(match[0].length); console.log(followingNode) // Wrap the target in an `a` element. // First we create the wrapper and insert it in front // of the target text. We use the first capture group // as the `href`. wrapper = document.createElement('img'); wrapper.style.backgroundColor = "yellow" wrapper.src = "fasd";//suche match targetNode.parentNode.insertBefore(wrapper, targetNode); // Now we move the target text inside it wrapper.appendChild(targetNode); // Clean up any empty nodes (in case the target text // was at the beginning or end of a text ndoe) if (node.nodeValue.length == 0) { node.parentNode.removeChild(node); } if (followingNode.nodeValue.length == 0) { followingNode.parentNode.removeChild(followingNode); } // Continue with the next match in the node, if any match = followingNode ? targetRe.exec(followingNode.nodeValue) : null; } }Pero a veces solo coincide con la primera palabra de una oración y también devuelve mucha basura, como código. ¿Cómo puedo filtrar eso?
Gracias por tu ayuda