I have some local HTML and CSS that I display using a UIWebview. I want to incorporate search hit highlighting.
Here is my highlighting method:
-(void) highlightsSearchTerm:(NSString *)searchTerm
{
NSString *highlightedSearchTerm = [NSString stringWithFormat:@"<span class='highlight'>%@</span>",searchTerm];
NSString *highlightedArticle = [article.articleHTML stringByReplacingOccurrencesOfString:searchTerm withString:highlightedSearchTerm options:NSCaseInsensitiveSearch range:NSMakeRange(0, [article.articleHTML length])];
article.articleHTML = highlightedArticle;
}
The issue with this is that it replaces, for example, Obama with the user’s search query, which might have been obama (note the case). I want to maintain the case of the original article while incorporating the hit highlighting.
I’m hoping for a more elegant solution than manually finding the starting and ending indexes of each hit term and then inserting <span class="highlights"> and ” respectively.
Basically I want something like:
+ [NSString stringByWrappingExistingString:(NSString *)stringToWrap withString:(NSString *)wrappingString options:NSCaseInsensitiveCompare];
Any thoughts?
You can use
NSRegularExpressionto do this (code typed in directly, check for errors):The regular expression search string,
@"Obama", is straightforward in this case as you are looking for a literal match; the optionoptions:NSRegularExpressionCaseInsensitivemakes the match case-insensitive.While the example uses a literal Obama you can obviously construct the string dynamically; however be careful in that case about using strings which contain regular expression meta-characters, they will need to be escaped.
The replace template contains
$0which will be replaced by what was matched (exactly, so preserving case).