简体   繁体   English

无法从字符串中删除 HTML 标签

[英]Unable to remove HTML tags from string

I am getting a property called "JobDescription" in response from an API which contains HTML tags inside.我从 API 得到一个名为“JobDescription”的属性,其中包含 HTML 标记。 I am trying to remove html tags from inside the string but its not working.我正在尝试从字符串内部删除 html 标记,但它不起作用。

Code:代码:

 var jobDescription= "<P> kajskjdhkj</p> <div> lakjsklj/div>";
 console.log($sce.trustAsHtml(jobDescription)); // output : {}

Expected Output:预期 Output:

kajskjdhkj lakjsklj

I know we use it with "ng-bind-html" directive.我知道我们将它与“ng-bind-html”指令一起使用。 Is it not possible to use it in the script to remove "html tags"?难道不能在脚本中使用它来删除“html标签”吗?

My last option would be to use "regex" or any other logic to remove the HTML tags from the string but my first option would be to stick to standard way of using $sce.trustAsHtml function.我的最后一个选择是使用“正则表达式”或任何其他逻辑从字符串中删除 HTML 标签,但我的第一个选择是坚持使用$sce.trustAsHtml function 的标准方式。

I use a filter for this sort of thing:我对这类事情使用过滤器:

app.filter('stripTags', function() {
        return function(text) {
            return text ? String(text).replace(/<[^>]+>/gm, '') : '';
        };
    })

Then in your controller:然后在您的 controller 中:

var jobDescription= "<P> kajskjdhkj</p> <div> lakjsklj</div>";
var jobDescription_notags = $filter("stripTags")(jobDescription)

Approach using angular.element(html).text()使用angular.element(html).text()方法

 angular.module('app', []).controller('main', function() { var jobDescription = "<P> kajskjdhkj</p> <div> lakjsklj</div>"; this.txt = angular.element(jobDescription).text() var sample ="Abc. Xyz Lmn No.1234 H, PPP TTT GGG, LKH 3</br>" this.txt2 = angular.element('<div>').html(sample).text() })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-app="app" ng-controller="main as $ctrl"> {{$ctrl.txt}}<br/><br/> {{$ctrl.txt2}} </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM