Enzo Tran Enzo Tran - 1 month ago 9
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

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];
    else
        [escapedString appendFormat:@"%c", *chars];
    ++chars;
}
NSString *js = [NSString stringWithFormat:@"my_js_function(\"%@\")", escapedString];
Comments