简体   繁体   English

从AngularJS中的字符串中删除HTML标签

[英]Remove HTML tag from string in AngularJS

I am getting HTML tags in my response, which I want to remove or parse it. 我在响应中得到HTML标记,我想将其删除或解析。

I got the output like 我得到的输出像

<sometext>

but I want output only 但我只想要输出

sometext

In the view, I have used the following code 在视图中,我使用了以下代码

<div ng-bind-html="description"></div>

And in controller 并在控制器中

 $scope.description = '&lt;sometext&gt;';

I would go with a chained regex replace like this to make sure you don't remove those '/' which are out of '<>' tags: 我将使用这样的链式正则表达式替换来确保您不会删除那些不在“ <>”标记中的“ /”:

var a = '<tag>hello</tag>'
var b = a.replace(/\/>/g,'')    // Remove self-closing tags right part that look like "/>" as in "<Tag/>"
         .replace(/<\//g,'')    // Remove "</" as in "</closing>"
         .replace(/[<>]/g,'');  // Remove the rest "<" or ">"
console.log(b) // taghellotag

This code is still not perfect as doesn't look for < and > used outside of tags. 这段代码仍然不是完美的,因为它不会寻找在标记之外使用的<>

Here is the fiddle: 这是小提琴:

 var a= '<tag>hello</tag>' var b = a.replace(/\\/>/g,'') .replace(/<\\//g,'') .replace(/[<>]/g,''); console.log(b) 

I am still not sure what are you after, but if you are looking for a the text-only content of your html, this should do it (I'm not sure whether it requires full jQuery or works with jQuery Lite though, I do have jQuery in my project): 我仍然不确定您要做什么,但是如果您正在寻找html的纯文本内容,则应该这样做(我不确定是需要完整的jQuery还是可以与jQuery Lite一起使用,我可以在我的项目中使用jQuery):

/* 'stripHTML': returns the concatenated text nodes of the html string provided */
MyApp.filter ('stripHTML', [function () {
    return function (stringWithHtml) {
        var strippedText =  $('<div/>').html(stringWithHtml).text();
        return strippedText;
    };
}]);

It's a (custom) angular filter, so you know how to use it. 这是一个(自定义)角度滤镜,因此您知道如何使用它。 If this is not what you wanted, then apologies. 如果这不是您想要的,则表示歉意。

Filters are used to modify the data in AngularJS. 过滤器用于修改AngularJS中的数据。 We can create our own custom filter to remove the HTML tags from a string. 我们可以创建自己的自定义过滤器,以从字符串中删除HTML标记。

Look at http://www.codeexpertz.com/blog/angularjs/remove-html-tags-angularjs-using-user-defined-filters-example-and-demo for Demo and Sample Code 查看http://www.codeexpertz.com/blog/angularjs/remove-html-tags-angularjs-using-user-defined-filters-example-and-demo以获得演示示例代码

Filter Code: 过滤器代码:

return text ? String(text).replace(/<[^>]+>/gm, '') : '';

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

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