Created
September 6, 2021 16:25
-
-
Save aderowbotham/658c6433cd8f337ee24e8aaffb9c682a to your computer and use it in GitHub Desktop.
Javascript replace HTML text but not affect attribute values in double quotes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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