如果你需要一個解決方案將與擴展ASCII符號(例如拉丁符號)和/或Unicode工作,你可以使用這個:
- (NSString*) escapeStringForJavascript:(NSString*)input
{
NSMutableString* ret = [NSMutableString string];
int i;
for (i = 0; i < input.length; i++)
{
unichar c = [input characterAtIndex:i];
if (c == '\\')
{
// escape backslash
[ret appendFormat:@"\\\\"];
}
else if (c == '"')
{
// escape double quotes
[ret appendFormat:@"\\\""];
}
else if (c >= 0x20 && c <= 0x7E)
{
// if it is a printable ASCII character (other than \ and "), append directly
[ret appendFormat:@"%c", c];
}
else
{
// if it is not printable standard ASCII, append as a unicode escape sequence
[ret appendFormat:@"\\u%04X", c];
}
}
return ret;
}
我不知道該怎麼行爲的代碼點高於unichar可表示的代碼點。看起來像這樣的字符不能用JavaScript來表示。
備案:'stringByEvaluatingJavaScriptFromString'爲Unicode正確;您不必轉義非ASCII字符。 – 2014-03-22 16:35:07