$.fn.wrapInTag = function(opts) {
var tag = opts.tag || 'strong',
words = opts.words || [],
regex = RegExp(words.join('|'), 'gi'),
replacement = '<' + tag + '>$&</' + tag + '>';
return this.html(function() {
return $(this).text().replace(regex, replacement);
});
};
$('p').wrapInTag({
tag: 'em',
words: ['html', 'CSS', 'JavaScript'],
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<p>O HTML d é muito usado nos dias de hoje, juntamente com o HTML usamos JavaScript e CSS...</p>
I'm having problems with RegExp in Jquery, I have a list of words it takes from < p > and places it inside < em & gt ;. It works almost right, however it does not respect whole words, if I search for HTML it returns HTML1, HTMLX, HTMLZ and not only HTML, if the HTML is along with other words it identifies the word also in the middle of others, it does not whole word.
What I look for is that:
- "HTML" stay: HTML
- "HTMLabc" is intact, without being italicized, only: HTMLabc;
My example code: link
Take the test by adding any letter on the front or behind the words html, CSS, and JavaScript you can see that it continues to consider words even though they have other characters together at the beginning or end of the word.