Remove HTML tags from a String in Dart

我怕爱的太早我们不能终老 提交于 2019-12-05 15:31:13

问题


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 the spaces) in between the string. Can anyone assist me in removing those tags so that I can get a plain string?


回答1:


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.




回答2:


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:


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




回答4:


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);
});



回答5:


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


来源:https://stackoverflow.com/questions/51593790/remove-html-tags-from-a-string-in-dart

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