Remove HTML tags from a String in Dart

前端 未结 5 1791
傲寒
傲寒 2020-12-17 09:00

I’ve been trying to achieve this for a while, I have a string which contains a lot of HTML tags in it which is in some encoded form Like & lt; and & gt; (without th

相关标签:
5条回答
  • 2020-12-17 09:16

    By just using

    import ‘package:html/parser.dart’;
    

    will get a problem, for those strings that includes <br> and <p> tags. Paragraph info is missing. May first replace <br> to <p>, then get List:

    import ‘package:html/parser.dart’  as dom; 
    
    htmlString = '<p> first ... line.<br>second.....line.<p>'; 
    
    List<String> cleanStrings = new List<String>();
    List<dom.Element> ps = parse(htmlString.replaceAll('<br>', '</p><p>'))).querySelectorAll('p');
    if (ps.isNotEmpty) ps.forEach((f) {
      (f.text != '') cleanStrings.add(f.text);
    });
    
    0 讨论(0)
  • 2020-12-17 09:18

    3 steps

    first, add this to your "pubspec.yaml" file

    dependencies: flutter_html: ^0.8.2

    second, import to your dart file

    import 'package:flutter_html_view/flutter_html_view.dart';

    3rd, simply use

    HtmlView(data: "Your Html Data"),

    0 讨论(0)
  • 2020-12-17 09:34

    Finally I achieved this using the html package

    Here’s how I did it

    import 'package:html/parser.dart';
    
    
    //here goes the function 
    String _parseHtmlString(String htmlString) {
    final document = parse(htmlString);
    final String parsedString = parse(document.body.text).documentElement.text;
    
    return parsedString;
    }
    

    I don’t know if there is any cleaner way to do this but this one worked for me.

    0 讨论(0)
  • 2020-12-17 09:36

    You can simply use RegExp without 3rd Lib

    String removeAllHtmlTags(String htmlText) {
        RegExp exp = RegExp(
          r"<[^>]*>",
          multiLine: true,
          caseSensitive: true
        );
    
        return htmlText.replaceAll(exp, '');
      }
    
    0 讨论(0)
  • 2020-12-17 09:40
    use this class:
    
    import 'package:html/parser.dart';
    
    class HtmlTags {
    
      static void removeTag({ htmlString, callback }){
        var document = parse(htmlString);
        String parsedString = parse(document.body.text).documentElement.text;
        callback(parsedString);
      }
    }
    
    example: 
    
    HtmlTags.removeTag(
     htmlString: '<h1>Hello Bug</h1>',
     callback: (string) => print(string),
    );
    output: Hello Bug
    
    0 讨论(0)
提交回复
热议问题