Remove HTML tags from a String in Dart

萝らか妹 提交于 2019-12-04 02:43:41

Finally I achieved this using the Dart’s built in html package

Here’s how I did it

import ‘package:html/parser.dart’;
//here goes the function 

String _parseHtmlString(String htmlString) {

var document = parse(htmlString);

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.

You can simply use RegExp without 3rd Lib

String removeAllHtmlTags(String htmlText) {
    RegExp exp = RegExp(
      r"<[^>]*>",
      multiLine: true,
      caseSensitive: true
    );

    return htmlText.replaceAll(exp, '');
  }

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"),

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);
});
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!