Remove HTML tags from a String in Dart
You can simply use RegExp without 3rd Lib for remove tag (
</>)
String removeAllHtmlTags(String htmlText) {
RegExp exp = RegExp(
r"<[^>]*>",
multiLine: true,
caseSensitive: true
);
return htmlText.replaceAll(exp, '');
}
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.
The intl
package provides a method stripHtmlIfNeeded
to strip the HTML tags from the string.
The Bidi
class under this package provides the utility method for working with the bidirectional text.
import 'package:intl/intl.dart';
Bidi.stripHtmlIfNeeded("<p>Hello World</p>")
If you don't want to use the whole package just for this function, below is the method implementation:
static String stripHtmlIfNeeded(String text) {
return text.replaceAll(RegExp(r'<[^>]*>|&[^;]+;'), ' ');
}
Documentation: https://api.flutter.dev/flutter/intl/Bidi/stripHtmlIfNeeded.html