Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - Wrap the whole word in a span element if the word includes combination of specific letters

i have code below which finds and wraps those words in a span element, but only them. i would like to wrap a whole word if it inludes those words. for example: GSHAA or GSH112

my code:

var words = ["GSHT","GSH","SHV"];

$('.list-icons a').html(function(_,html) {
    var reg = new RegExp('('+words.join('|')+')','gi');
    return html.replace(reg, '<span class="wrap">$1</span>', html)
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order for your regular expression to match the entire word instead of only the substring, you should check for the word boundary using . 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...