Getting whole words with RegExp in Jquery

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><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.

    
asked by anonymous 11.12.2016 / 21:58

1 answer

3

You can add a negation rule to each word. It would look like this:

regex = RegExp('(\W|^)(' + words.join('|') + ')(\W|$)', 'gi'),

and thus you would have a regex like this:

/(\W|^)(html|CSS|JavaScript)(\W|$)/gi

and then an important step:

replacement = '$1<' + tag + '>$2</' + tag + '>$3';

which causes it to index what was captured within each of the () catch groups and places it in the right place of the new string to be formed.

So, in practice it prevents match if there is a letter or number before or after of the paravra you indicated.

jsFiddle: link

regex: link

    
11.12.2016 / 22:14