Highlight Words in HTML Using Regex & JavaScript - Almost There

highlight words in html using regex & javascript - almost there

Just use jQuerys built-in text() method. It will return all the characters in a selected DOM element.

For the DOM approach (docs for the Node interface): Run over all child nodes of an element. If the child is an element node, run recursively. If it's a text node, search in the text (node.data) and if you want to highlight/change something, shorten the text of the node until the found position, and insert a highligth-span with the matched text and another text node for the rest of the text.

Example code (adjusted, origin is here):

(function iterate_node(node) {
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);
iterate_node(rest); // maybe there are more matches
}
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
for (var i = 0; i < node.childNodes.length; i++) {
iterate_node(node.childNodes[i]); // run recursive on DOM
}
}
})(content); // any dom node

There's also highlight.js, which might be exactly what you want.

highlight words in html using regex in C#

I'll offer up a solution, but I agree that solely using Regex for parsing HTML can eventually not be worth the effort. That said, you know more about your problem space than the rest of us, so if the HTML you're highlighting is under your control you may be able to test enough of your domain to achieve what you want with regexes.

My solution changes the regex you've supplied to take this approach:

  1. Match and capture into $1 the > char, non-greedy capture chars not in set [<>]
  2. Match and capture your keyword into $2
  3. Match and capture into $3 non-greedy chars not in set [<>], plus the < char

Caveats:

  1. well-formed HTML works best, if this html is User-Generated content (UGC), then, good luck you should've used an HTML parser :)
  2. this would highlight content within <textarea>...</textarea>
  3. this would highlight content within <script>...</script>

Note you could expand the capture on the lefthand side to capture the tag name and conditionally not replace for a set of tags like textarea and script.

string searchString = "ABC";
string content = "<div><img src='/site/folder/ABC.PNG' /><br />ABC</div>";
string replacePattern = "$1<span style=\"background-color:yellow\">$2</span>$3";
string searchPattern = String.Format("(>[^<>]*?)({0})([^<>]*?<)", searchString.Trim());
content = Regex.Replace(content, searchPattern, replacePattern, RegexOptions.IgnoreCase);
Console.WriteLine(content);

Javascript: highlight substring keeping original case but searching in case insensitive mode

Use a function for the second argument for .replace() that returns the actual matched string with the concatenated tags.

Try it out: http://jsfiddle.net/4sGLL/

reg = new RegExp(querystr, 'gi');
// The str parameter references the matched string
// --------------------------------------v
final_str = 'foo ' + result.replace(reg, function(str) {return '<b>'+str+'</b>'});
$('#' + id).html(final_str);​

JSFiddle Example with Input: https://jsfiddle.net/pawmbude/

Highlighting lines that contain a phrase using regex

You may want to match all chars other than < and > before and after the text and it is advisable to escape the literal text you pass to the RegExp constructor. Also, to replace with the whole match, just use $& placeholder:

const START = "<span name='highlight' style='background-color: yellow;'>";const END   = "</span>"
function highlight(text, toReplace) { let reg = new RegExp("(<br/?>)|[^<>]*" + toReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "[^<>]*", 'ig'); return text.replace(reg, function ($0,$1) { return $1 ? $1 : START + $0 + END; });}console.log(highlight("This<br>is some text to<br>highlight.", "text"));
console.log(highlight("This<br>is a bunch of<br>text", "b"));

Javascript: Highlighting part of a string with b tags

See "Escape Regular Expression Characters in String - JavaScript" for information about how to escape special regex characters, such as ()

EDIT: Also check out this older SO question that asks a very similar - almost identical - question.

Highlighting a specific text which in html raw text

You're almost there, but in Angular, code between double braces {{<code>}} will be rendered as escaped html text (plain text). In order to your string be rendered as html, it must be in the attribute innerHTML of your parent element, like this:

<div #rawContentContext class="form-group m-form__group row col-lg-12"
style="width:100%; height: 100vh; overflow:scroll;"
[innerHTML]="getHtmlRawContent() | highlight:getSearchedKeyWord()">
</div>

Highlighting text in document (JavaScript) Efficiently

<html>
<head>
</head>
<body>
<p id="myText">"My generic words would be selected here" !.</p>
<script>
//highlight code here
var textToHighlight = 'selected here" !';
var text = document.getElementById("myText").innerHTML
document.getElementById("myText").innerHTML = text.replace(textToHighlight, '<span style="color:red">'+textToHighlight+'</span>');
//what sould I write here?
</script>
</body>
</html>


Related Topics



Leave a reply



Submit