Enzo Tran Enzo Tran - 2 years ago 188
Javascript Question

Escape NSString for javascript input

I have a string of ASCII characters (created randomly by [NSString stringWithFormat:@"%c", someNumber]), and I want to use that string as input for a javascript method. Something like:

[webView_ stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"my_javascript_method(\"%@\")", myASCIIString]];

How can I escape the NSString? I tried to look into encodeURI and decodeURI, but haven't found any solution yet.

Answer Source

By ASCII, I presume you mean it's a byte in the range 0x00 to 0x7F. In this range, according to http://www.json.org the only characters you need to escape are \, ", and the control characters: 0x00-0x1F and 0x7F. The control characters get a bit tricky if you're doing simple substitutions, so I'd go through character by character to escape the string, maybe something like this (not tested at all):

const char *chars = [myASCIIString UTF8String];
NSMutableString *escapedString = [NSMutableString string];
while (*chars)
    if (*chars == '\\')
        [escapedString appendString:@"\\\\"];
    else if (*chars == '"')
        [escapedString appendString:@"\\\""];
    else if (*chars < 0x1F || *chars == 0x7F)
        [escapedString appendFormat:@"\\u%04X", (int)*chars];
        [escapedString appendFormat:@"%c", *chars];
NSString *js = [NSString stringWithFormat:@"my_js_function(\"%@\")", escapedString];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download