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

时间:2015-10-16 09:51:58

标签: javascript swift

在评估Javascript时,例如:

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

如何确保消息属于String类型,我可以安全地传递给此方法?我可以想象一句话或换行会让事情搞得一团糟。

2 个答案:

答案 0 :(得分:1)

只需使用stringByReplacingOccurrencesOfString()替换引号,也可以为方便起见创建扩展名:

extension String {
    var stringWithoutQuote: String {
        return self.stringByReplacingOccurrencesOfString("'", withString: "").stringByReplacingOccurrencesOfString("\"", withString: "")
    }
}

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

答案 1 :(得分:0)

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
    }
}