AngularJS replace using regex

I have to replace HTML (matched words) of a page on load. I only need to replace the words matched within <div> and <p> tags though. I am using angularJS for this.

My function so far -

var elementsList = e.find('p');

var regex = ('[^<>\\n]*?\\b(Cat|Dog|Fish)\\b[^<>\\n]*?', 'gi');                 

angular.forEach(elementsList, function(_element){
    var eHtml = $(_element).html();
    e.html(eHtml .replace(regex, function(fullMatch, match){
    if(angular.isString(match))
    {
         return 'TEST' + match;
    }
    }));
    $compile($(_element).html())($scope);
  });                                                                 

$compile(e.contents())($scope);

But this isn't updating the html of the page correctly. It replaces the whole sentence instead of just replacing the matched word.

So for example the html is

<p>I am a dog.</p>
<p>I am a cat.</p>
<p>I am not a dog but a cat.</p>

I want the result to be

<p>I am a TESTdog.</p>
<p>I am a TESTcat.</p>
<p>I am not a TESTdog but a TESTcat.</p>

As i see you confused element with full html and element for concrete <p> tag.

here

angular.forEach(elementsList, function(_element){

you go to elementList that contains <p> tag and _element refers to concrete <p> from this list, but next you get html from this element

var eHtml = $(_element).html();

replace it

eHtml.replace(regex, function(fullMatch, match){ ... })

and instert in main e element

e.html(eHtml.replace(...))

so instead replace html for concrete tag, you replace full html, and do this on each loop iteration.

So possibly you sould use $(_element) instead just e

$(_element).html(eHtml.replace(...))

UPDATE also seems you regex can be reduced to

/\b(Cat|Dog|Fish)\b/gi

and used like

var regex = /\b(Cat|Dog|Fish)\b/gi;
$(_element).html(eHtml.replace(regex, "Test$1"));