How to Remove HTML tags from String in Flutter/Dart

In this example, we are going to show you how to strip HTML tags from String in Dart/Flutter. Using the example below, you can convert any kind of HTML to String in Flutter.

See this also: How to Convert/Show HTML as Widget in Flutter

String html = '<div><p>Hello</p>This is <br/>fluttercampus.com<span>,Bye!</span></div>';

RegExp exp = RegExp(r"<[^>]*>",multiLine: true,caseSensitive: true);
String parsedstring1 = html.replaceAll(exp, '');
print(parsedstring1);
//output without space:  HelloThis is fluttercampus.com,Bye!

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.

Integrate html flutter package in your project by adding the following lines in your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  html: ^0.15.0

Remove HTML tags:

import 'package:html/parser.dart';
String html = '<div><p>Hello</p>This is <br/>fluttercampus.com<span>,Bye!</span></div>';

var doc = parse(html);
if(doc.documentElement != null){
    String parsedstring = doc.documentElement!.text;
    print(parsedstring); 
    //output without space: HelloThis is fluttercampus.com,Bye!   
}

Install intl package on your project by adding following lines in pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.17.0

Remove HTML tags:

import 'package:intl/intl.dart';
String html = '<div><p>Hello</p>This is <br/>fluttercampus.com<span>,Bye!</span></div>';

//Bidi.stripThmlIfNeeded() method is from intl package
String parsedstring3 = Bidi.stripHtmlIfNeeded(html);
print(parsedstring3);
//output with space:   Hello This is  fluttercampus.com ,Bye!

You can see the documentation of stripHtmlIfNeeded on this link. If you don't want to use the whole package for this single method. you can declare the method anywhere and use it in your project. The method on the documentation is:

static String stripHtmlIfNeeded(String text) {
  // The regular expression is simplified for an HTML tag (opening or
  // closing) or an HTML escape. We might want to skip over such expressions
  // when estimating the text directionality.
  return text.replaceAll(RegExp(r'<[^>]*>|&[^;]+;'), ' ');
}

In this way, you can remove HTML tags from strings in Dart/Flutter.

No any Comments on this Article


Please Wait...