It depends on when / what you need to get the name. If you need a name when someone clicks on the link, you can configure JavaScript to run when the link is clicked (onclick handler). If you only have the html string, you can use regular expressions to parse the document and pull out all the name attributes. A good regex library for Objective-C is RegexKit (or RegexKitLite on the same page).
The regular expression for parsing the name attribute outside the link will look something like this:
/<a[^>]+?name="?([^" >]*)"?>/i
EDIT: javascript to get the name from the link when someone clicked it would look something like this:
function getNameAttribute(element) { alert(element.name);
This will be called from the onclick handler, for example:
<a href="http://www.google.com/" name="anElementName" onclick="getNameAttribute(this)">My Link</a>
If you need to return the name to your Objective-C code, you can write your onclick function to add the name attribute to the url in the form of a hashtag, and then catch the request and -webView:shouldStartLoadWithRequest:navigationType: it in your UIWebView delegate -webView:shouldStartLoadWithRequest:navigationType: It will look something like this:
function getNameAttribute(element) { element.href += '#'+element.name; } //Then in your delegate .m file - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSArray *urlParts = [[request URL] componentsSeparatedByString:@"#"]; NSString *url = [urlParts objectAtIndex:0]; NSString *name = [urlParts lastObject]; if([url isEqualToString:@"http://www.google.com/"]){ //Do something with `name` } return FALSE; //Or TRUE if you want to follow the link }
source share