首页 文章

Angular JS正则表达式替换

提问于
浏览
2

这个问题是Regex match whole word including whitespace and fullstop的延续

我最终使用的正则表达式是 (<(p|li)\b[^<>]*>[^<>\n]*)\b(Cat|Dog|Fish)\b([^<>\n]*<\/\2>)

现在,我需要用其他HTML替换匹配的单词 .

帮助我构建这个正则表达式的Vks建议我可以访问 $3 变量来获取匹配的单词 . 但我似乎无法做到这一点 . (https://regex101.com/r/oC5rY5/12#javascript

我正在尝试在Angular JS中进行替换,这是我不太熟悉的 .

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;
});

我如何在这里访问 $3match 不回馈匹配的单词 . 尝试使用 match[3] ,但这也不起作用 .

请注意,我的替换不仅仅是1个字符串,而是整个页面的HTML,因此需要递归 .

1 回答

相关问题