如何转义 UIWebView 的字符串?

发布于 2024-10-27 02:06:00 字数 569 浏览 1 评论 0原文

我从服务器提取 json 数据。它包含一个字典,其中包含我插入到 html 模板中的文本。

如何正确转义该字符串?

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json someEscapeMethod]; ///////  HOW TO ESCAPE THIS ?
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];

我目前确实喜欢这样做,但我不确定转义是否足够

NSString* json_escaped = [json stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];

I pull json data from a server. It contains a dictionary with text that I insert into a html template.

How do I properly escape this string?

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json someEscapeMethod]; ///////  HOW TO ESCAPE THIS ?
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];

I currently do like this, but I'm not sure wether the escaping is sufficiently

NSString* json_escaped = [json stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私野 2024-11-03 02:06:00

我现在就这样编码,但是开销很大。

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];

并像这样用 javascript 对其进行解码

function process(json_escaped) {
  var json = decodeURIComponent(json_escaped);
  alert('json: ' + json.toString());
}

我仍在寻找开销更少的更好的解决方案。

更新

我最近了解到,存在多个用于桥接 Objective-C 和 javascript 的框架

I now encode it this way, but the overhead is huge.

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];

And decode it in javascript like this

function process(json_escaped) {
  var json = decodeURIComponent(json_escaped);
  alert('json: ' + json.toString());
}

I'm still looking for a better solution with less overhead.

Update

I have recently learned that there exists several frameworks for bridging objective-c with javascript.

っ〆星空下的拥抱 2024-11-03 02:06:00

The "Escaping Characters in a String" section of NSRegularExpression may work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文