Remove Markdown tags from Attributed String similar to Text Box in Stackoverflow

| | August 6, 2015

I am trying to make a UITextView that supports Markdown syntax just like the text box used by this website. I want to create a preview that removes the tags from an attributed text. For example **bold** becomes **bold** and I just want bold. I’m not sure how to remove all the tags. I don’t want to lose the attribute. Here is what I have so far

NSCharacterSet *charactersToRemove =
[[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];

attributedString = [[attributedString attributedStringByTrimming:charactersToRemove] mutableCopy];

In a category I have the following code:

- (NSAttributedString *)attributedStringByTrimming:(NSCharacterSet *)set {
NSCharacterSet *invertedSet = set.invertedSet;
NSString *string = self.string;
unsigned int loc, len;

NSRange range = [string rangeOfCharacterFromSet:invertedSet];
loc = (range.length > 0) ? (int)range.location : 0;

range = [string rangeOfCharacterFromSet:invertedSet options:NSBackwardsSearch];
len = (range.length > 0) ? (int)NSMaxRange(range) - loc : (int)string.length - loc;

return [self attributedSubstringFromRange:NSMakeRange(loc, len)];
}

Leave a Reply