How do I encode "&" in a URL in an HTML attribute value?

41,657

Solution 1

the ampersand would be %26 for HEX in URL Encoding standards

Solution 2

I've been using -[NSString gtm_stringByEscapingForURLArgument], which is provided in Google Toolbox for Mac, specifically in GTMNSString+URLArguments.h and GTMNSString+URLArguments.m.

Solution 3

you can simply use CFURLCreateStringByAddingPercentEscapes with CFBridgingRelease for ARC support

NSString *subject = @"This is a test";
// Encode all the reserved characters, per RFC 3986
// (<http://www.ietf.org/rfc/rfc3986.txt>)
NSString *encodedSubject =
(NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)subject,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8));

Solution 4

You can use a hex representation of the character, in this case %26.

Solution 5

You use stringByAddingPercentEscapesUsingEncoding, exactly like you are doing.

The problem is that you aren't using it enough. The format into which you're inserting the encoded body also has an ampersand, which you have not encoded. Tack the unencoded string onto it instead, and encode them (using stringByAddingPercentEscapesUsingEncoding) together.

Share:
41,657
4thSpace
Author by

4thSpace

Updated on November 21, 2020

Comments

  • 4thSpace
    4thSpace over 3 years

    I'd like to make a URL click able in the email app. The problem is that a parameterized URL breaks this because of "&" in the URL. The body variable below is the problem line. Both versions of "body" are incorrect. Once the email app opens, text stops at "...link:". What is needed to encode the ampersand?

    NSString *subject = @"This is a test";
    NSString *encodedSubject = 
    [subject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    
    //NSString *body = @"This is a link: <a href='http://somewhere.com/two.woa/wa?id=000&param=0'>click me</a>"; //original
    NSString *body = @"This is a link: <a href='http://somewhere.com/two.woa/wa?id=000&#38;param=0'>click me</a>"; //have also tried &amp;
    NSString *encodedBody = 
    [body stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSString *formattedURL = [NSString stringWithFormat: @"mailto:[email protected]?subject=%@&body=%@", encodedSubject, encodedBody];
    NSURL *url = [[NSURL alloc] initWithString:formattedURL];
    [[UIApplication sharedApplication] openURL:url];