Skip to content Skip to sidebar Skip to footer

How Can I Get Name From Link?

I'm writing on objective-C. I have WebView and local file index.html has How can I get the name attribute? Thanks!

Solution 1:

It depends on when/by what you need to get the name. If you need the name when someone clicks on the link, you can set up some JavaScript that runs when the link is clicked (onclick handler). If you just have the html string, you can use regular expressions to parse the document and pull out all of the name attributes. A good regular expression library for Objective-C is RegexKit (or RegexKitLite on the same page).

The regular expression for parsing the name attribute out of a link would look something like this:

/<a[^>]+?name="?([^" >]*)"?>/i

EDIT: The javascript for getting a name out of a link when someone clicked it would look something like this:

function getNameAttribute(element) {
    alert(element.name); //Or do something else with the name, `element.name` contains the value of the name attribute.
}

This would be called from the onclick handler, something like:

<ahref="http://www.google.com/"name="anElementName"onclick="getNameAttribute(this)">My Link</a>

If you need to get the name back to your Objective-C code, you could write your onclick function to append the name attribute to the url in the form of a hashtag, and then trap the request and parse it in your UIWebView delegate's -webView:shouldStartLoadWithRequest:navigationType: method. That would go something like this:

function getNameAttribute(element) {
    element.href += '#'+element.name;
}

//Then in your delegate's .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`
    }

    returnFALSE; //Or TRUE if you want to follow the link
}

Post a Comment for "How Can I Get Name From Link?"