Skip to content

Instantly share code, notes, and snippets.

@aderowbotham
Created September 6, 2021 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aderowbotham/658c6433cd8f337ee24e8aaffb9c682a to your computer and use it in GitHub Desktop.
Save aderowbotham/658c6433cd8f337ee24e8aaffb9c682a to your computer and use it in GitHub Desktop.
Javascript replace HTML text but not affect attribute values in double quotes
// javascript (ES5)
function highlight(content, term, startWrapper, endWrapper){
// negative match for the pattern surrounded by quotes ""
// followed by positive match for the term on its own
// the required pattern is as follows but we have to use RegExp() to set the term dynamically
// regex = /(?!"*term*")(?:term)/ig
var expression = new RegExp('(?!"*' + term + ' *")(?:' + term + ')', "i");
return content.replace(expression, startWrapper + content.match(expression) + endWrapper);
}
<!-- HTML where we want to find '1234' and wrap in highlight tags: <i class="highlight">1234</i> -->
<body>
<div>
<a id="1234">1234</a>
</div>
<div>
<a id="5678">5678</a>
</div>
<script>
// example with jQuery
var term = "1234"
$("div").each(function() {
var content = $(this).html();
$(this).html(highlight(content, term, "<i class=\"highlight\">", "</i>"));
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment