Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove HTML tags from a String in Dart

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?

like image 867
Jaswant Singh Avatar asked Jul 30 '18 12:07

Jaswant Singh


People also ask

How to remove HTML tags from string in dart?

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.

How do I remove a tag from a string?

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.

How do I convert HTML to plain text in flutter?

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.


3 Answers

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.

like image 181
Jaswant Singh Avatar answered Oct 23 '22 12:10

Jaswant Singh


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, '');
  }
like image 65
Phat Tran Avatar answered Oct 23 '22 11:10

Phat Tran


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

like image 18
Sudeep Bashistha Avatar answered Oct 23 '22 11:10

Sudeep Bashistha