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?
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. Show activity on this post.
The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.
String parsedstring2 = html. replaceAll(exp, ' '); print(parsedstring2); //output with space: Hello This is fluttercampus.com ,Bye! Here, we remove all HTML tags using Regex expression. You can also use RegExp(r'<[^>]*>|&[^;]+;') to strip HTML tags.
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.
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, '');
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With