2

This question is in continuation of Regex match whole word including whitespace and fullstop

The regex that I finally ended up using is (<(p|li)\b[^<>]*>[^<>\n]*)\b(Cat|Dog|Fish)\b([^<>\n]*<\/\2>)

Now, I need to replace the matched word with some other HTML.

Vks, who helped me build this regex advised that I can access $3 variable to get the matched word. But I can't seem to make that work. (https://regex101.com/r/oC5rY5/12#javascript)

I am trying to do the replace in Angular JS, something that I am not very familiar with.

html.replace(regex, function(fullMatch, match) {
    if (angular.isString(match)) {
        var abc = fullMatch.length > match.length ? fullMatch[0] : '';

        //Custom function to fetch data based on the matched word.
        var obj = $scope.getMoreInfo(match);
        if (angular.isObject(obj)) {
            return abc + '<div class="test123" url="' + obj.Url + '" text="' + match + '">' + match + '</div>';
        }
    }
    return fullMatch;
});

How do I access $3 here? match doesn't give back the matched word. Tried using match[3] but that doesn't work either.

Please note that my replace is not just for 1 string but the whole page's HTML, so it needs to be recursive.

Community
  • 1
  • 1
NomadTraveler
  • 1,086
  • 1
  • 12
  • 37
  • this may help you http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression – vks Jul 27 '15 at 06:51
  • I have had a look at it, @vks. It doesn't work with a bunch of HTML lines. – NomadTraveler Jul 27 '15 at 07:03

1 Answers1

0

You can get the matched groups in replace function by positional arguments. First argument is the match then p1, p2 and so on are the matched groups. So in your case you can get the third match like this.

html.replace(regex, function(match, p1, p2, p3, p4) {
    console.log(p3);
});

For more info see the reference here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

Ehtesham
  • 2,967
  • 1
  • 18
  • 20