3
$.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>
<script src="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 that it takes from <p> and puts inside the <em>. It works almost right, however it does not respect whole words, if I look 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 respect an entire word.
What I seek is that:
- "HTML" stay: HTML
- "Htmlabc" remain intact, not italicized, only: Htmlabc;
My example code: http://jsbin.com/zopilefevu/edit?html,js,output
Do the test by adding any letter in front of or behind the words html, CSS, and Javascript you can see that it continues to consider the words even though it has other characters together at the beginning or end of the word.
It works for me... you can explain better how to reproduce the problem?
– Sergio
Does this work as you want? https://jsfiddle.net/hrmgwjxf/ (is equal to your jsBin)
– Sergio
Hello good night, that’s how the text has the words HTML, CSS and JS. If you put another character in front of the HTML for example abcHTML, it keeps considering the HTML I would like it to respect the words since HTML is different from abcHTML.
– Patrick A Lima
ah... okay, I get it.
– Sergio
There’s a way to fix it ?
– Patrick A Lima