In order for your regular expression to match the entire word instead of only the substring, you should check for the word boundary using \b
. See this solution:
var words = ["a", "b", "c"];
// To prevent errors when looking for words with special characters
const escapeRegex = (str) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
$('.list-icons a').html(function(_, html) {
const query = words.map(escapeRegex).join('|');
const regex = new RegExp(`(\\b\\w*(?:${query})\\w*\\b)`, 'gi');
return html.replace(regex, '<span class="wrap">$1</span>')
});
.wrap {
background: black;
color: white
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list-icons">
<li><a>Apple pie ice</a></li>
<li><a>Blueberry cake</a></li>
<li><a>Honey</a></li>
</ul>
Simplified, (\\b\\w*word\\w*\\b)
means "look for a string that begins with a word boundary (a space or a newline), then your word
followed and preceded by any amount of alphanumeric characters (\w*
) and ends with a word boundary again".
Because you are inserting your words into a regular expression, you should escape them so that special characters (like $ . and +) do not cause regex parsing errors. I took and modified escapeRegex
from this answer.