Jayr Parro

Strip HTML Tag in NSString

This is a handy method to strip the HTML Tags in NSString object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+(NSString *)flattenHTML:(NSString *)html
{
  NSScanner *thescanner;
  NSString *text = nil;
  thescanner = [NSScanner scannerWithString:html];
  
  while ([thescanner isAtEnd] == NO) {
      //find start of tag
      [thescanner scanUpToString:@"<" intoString:nil];

      //find end of tag
      [thescanner scanUpToString:@">" intoString:&text];

      //replace the found tag with a space
       //(you can filter multi-spaces out later if you wish)
      html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
  }

   // Trimmed return
   return [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

Thanks to the original poster.
I’ve just change the return string to trim whitespaces.

Cheers!

Comments