You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C中loadHTMLString加载JS时\n转义失效问题求助

解决Objective-C中loadHTMLString加载JS字符串时\n未保留的问题

核心原因

Objective-C中的\n是转义字符,会被直接解析为实际换行;当插入到JS字符串中时,要么被浏览器处理为空格,要么触发JS语法错误(单引号字符串内的实际换行不符合语法规则)。要让JS识别到\n转义序列,必须在Objective-C字符串中对反斜杠进行双重转义。

解决方案1:手动转义换行符

将原字符串中的\n替换为\\n,确保Objective-C解析后,JS代码中保留\n转义序列:

// 原始带换行的字符串
NSString *originalSource = @"Product:A\nProduct:B\nProduct:C";
// 转义换行符(将\n转为\\n)
NSString *escapedSource = [originalSource stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
// 可选:转义单引号,避免JS语法错误(如果字符串含单引号)
escapedSource = [escapedSource stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
// 拼接HTML字符串
NSString *htmlString = [NSString stringWithFormat:@"<script>var source = '%@';</script>", escapedSource];
// 加载HTML
[self.webView loadHTMLString:htmlString baseURL:nil];

生成的JS代码会是:var source = 'Product:A\nProduct:B\nProduct:C',完全符合预期。

解决方案2:用JSON自动序列化(更可靠)

利用JSON序列化自动处理所有特殊字符(包括\n、单引号、双引号等),无需手动转义,覆盖所有边缘情况:

NSString *originalSource = @"Product:A\nProduct:B\nProduct:C";
// 将字符串序列化为JSON格式(自动转义特殊字符)
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:originalSource options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// 拼接HTML(注意这里不需要加单引号,JSON字符串本身带双引号)
NSString *htmlString = [NSString stringWithFormat:@"<script>var source = %@;</script>", jsonString];
[self.webView loadHTMLString:htmlString baseURL:nil];

内容的提问来源于stack exchange,提问作者E Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:20:43