Breaking News
Home / iOS / iOS Snippets / How to remove HTML tags from a String in iOS?

How to remove HTML tags from a String in iOS?

Sprite Fading Effects

Say you are scraping a feed or a page or parsing RSS feed, and the content that you are interested in say Title has some html elements in it (normally is an image) but you want to strip out the html elements and just display the text(making it more readable). In such cases the below snippet helps to strip out any HTML tags and replace them with a space comes to rescue. It basically uses NSScanner to scan to find the beginning of the html tag < till it find the end of the tag >, then it replaces the inner text with a space.


Code Snippet

The following code snippet shows the main methods.

  1. + (NSString *)flattenHtml: (NSString *) html {
  2.         NSScanner *theScanner;
  3.         NSString *text = nil;
  4.         theScanner = [NSScanner scannerWithString: html];
  5.         while ([theScanner isAtEnd] == NO) {
  6.                 // find start of tag
  7.                 [theScanner scanUpToString: @“<“ intoString: NULL];
  8.                 // find end of tag
  9.                 [theScanner scanUpToString: @“>” intoString: &text];
  10.                 // replace the found tag with a space
  11.                 //(you can filter multi-spaces out later if you wish)
  12.                 html = [html stringByReplacingOccurrencesOfString:
  13.                         [NSString stringWithFormat: @“%@>”, text]
  14.                         withString: @” “];
  15.         } // while //
  16.         return html;
  17. }

Check Also

EKCalendar – That account does not allow calendars to be added or removed

Usecase When I am trying to create a new Calendar programmatically using the EventKit API …

Advertisment ad adsense adlogger