Suppose an HTML page like this:
<h1>My page</h1>
<div>This is an HTML page...</div>
<div>Hello. Welcome to HTML, HTML5 is easy to learn</div>
I want to highlight all words individually, but not any special character or number.
I tried the following code, but my regular expression doesn't match:
if (node.nodeType === 3) { // Node.TEXT_NODE
var text = node.data,
pos = text.search(/any regular expression/g), //indexOf also applicable
length = 5; // Or whatever you found
if (pos > -1) {
node.data = text.substr(0, pos); // Split into a part before...
var rest = document.createTextNode(text.substr(pos+length)); // A part after
var highlight = document.createElement("span"); // And a part between
highlight.className = "highlight";
highlight.appendChild(document.createTextNode(text.substr(pos, length)));
node.parentNode.insertBefore(rest, node.nextSibling); // insert after
node.parentNode.insertBefore(highlight, node.nextSibling);
}
}
How do I write a regular expression that takes only words and not spaces or special characters?
Aucun commentaire:
Enregistrer un commentaire