gpt4 book ai didi

javascript - 如何在 Swift 中创建 Javascript 安全字符串?

转载 作者:行者123 更新时间:2023-11-30 10:10:30 24 4
gpt4 key购买 nike

评估 Javascript 时,例如:

self.evaluateJavaScript("window.messenger.sendMessage('\(message)');

如何确保消息是 String 类型,可以安全地传递到此方法中?我可以想象引用或换行符已经把事情搞砸了。

最佳答案

extension String {
var javaScriptString: String {
var safeString = self as NSString

safeString = safeString.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
safeString = safeString.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
safeString = safeString.stringByReplacingOccurrencesOfString("\'", withString: "\\\'")
safeString = safeString.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
safeString = safeString.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
safeString = safeString.stringByReplacingOccurrencesOfString("\t", withString: "\\t")

safeString = safeString.stringByReplacingOccurrencesOfString("\u{0085}", withString: "\\u{0085}")
safeString = safeString.stringByReplacingOccurrencesOfString("\u{2028}", withString: "\\u{2028}")
safeString = safeString.stringByReplacingOccurrencesOfString("\u{2029}", withString: "\\u{2029}")

return safeString as String
}
}

关于javascript - 如何在 Swift 中创建 Javascript 安全字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33167450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com