gpt4 book ai didi

html - 突出显示具有 html 实体的字符串的一部分作为文本 : angularJs

转载 作者:行者123 更新时间:2023-11-28 03:08:06 25 4
gpt4 key购买 nike

我有:

$scope.text = "<b>TESTNAME</b>"; (This can be any string. This is to specify that there can be html tags written as text in the string.)

粗体标签是文本的一部分,只需要显示为文本而不是 HTML。

现在假设有人输入搜索字符串(例如..任何人都可以输入任何字符串):

$scope.searchTerm = "NAME";

然后我希望 $scope.text 得到修改,以便我看到 <b>TESTNAME</b>但突出显示了“NAME”的子字符串。

我的突出显示功能:

$scope.text = $scope.text.replace(new RegExp("(" + $scope.searchTerm + ")","gi"), "<span class='highlighted'>\$1</span>");

在 HTML 中我必须写:

<span ng-bing-html="text"></span>

但是,现在出现的问题是,<b></b>也以 HTML 形式呈现,并将中间的字符串加粗。

如何处理?

编辑为了避免 b 标签呈现为 HTML,我使用以下方法将尖括号修改为对应的 HTML:

$scope.text = $scope.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

使用上面提到的第一个replace函数之后。现在,当使用 ng-bing-html 呈现 $scope.text 时,b 标签仅呈现为文本。但是,现在添加的 span 标签也呈现为文本,因为尖括号已被全局替换。

编辑处理该问题的另一种方法是我在添加 span 标签以突出显示文本之前替换了 Angular 标签。所以我的突出显示功能是:

  $scope.text = $scope.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
$scope.searchTerm = $scope.searchTerm.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
$scope.text = $scope.text.replace(new RegExp("(" + $scope.searchTerm + ")","gi"), "<span class='highlighted'>\$1</span>");

但是,问题是如果用户搜索字符串 ltgt ,然后由于对 < 和 > 进行了替换,突出显示跨度也被添加到这些内容中,最终结果与预期不同。

最佳答案

请检查工作示例:DEMO

Controller :

var app = angular.module('plunker', ["ngSanitize"]);

app.controller('MainCtrl', function($scope) {
$scope.searchTerm = "NAME";
$scope.content = "TESTNAME";
$scope.matchClass = 'bold';
var re = new RegExp($scope.searchTerm, 'g');
$scope.content = $scope.content.replace(re, '<span class="' + $scope.matchClass + '">' + $scope.searchTerm + '</span>');
});

HTML

<body ng-controller="MainCtrl">
<p ng-bind-html="content"></p>
</body>

CSS

.bold {
font-weight: bold;
}

关于html - 突出显示具有 html 实体的字符串的一部分作为文本 : angularJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31696537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com