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

如何移除字符串数组特定符号并拼接为HTML字符串?

问题解决

你的核心问题是误解了数组的存储形式:["<h2>...</h2>", "<h2>...</h2>"] 是数组的打印展示格式,并非数组元素的实际内容。数组里的每个元素就是纯HTML字符串(比如第一个元素是<h2>Some text, and some info.</h2>),不存在["、", "、"]这些符号,所以你写的数组扩展和正则替换完全找错了目标。

正确的实现步骤应该是:

  • 把数组中的所有HTML字符串拼接成一个完整的字符串
  • 对拼接后的字符串进行HTML转义,将<替换为&lt;,>替换为&gt;

直接用下面的代码即可实现需求:

if let result = ResultCoreDataManager.sharedInstance.getResults() {
    // 拼接数组内所有HTML字符串
    let combinedHTML = result.joined()
    // 转义HTML标签的尖括号
    let escapedHTML = combinedHTML
        .replacingOccurrences(of: "<", with: "&lt;")
        .replacingOccurrences(of: ">", with: "&gt;")
    // escapedHTML就是你需要的最终结果
}

如果你的Core Data实际存储的不是[String]数组,而是一个看起来像数组的字符串(比如直接存了["<h2>...</h2>", "<h2>...</h2>"]这样的文本),那需要先解析这个字符串:

if let resultString = ResultCoreDataManager.sharedInstance.getResultString() {
    // 移除数组格式符号
    let rawHTML = resultString
        .replacingOccurrences(of: "[\"", with: "")
        .replacingOccurrences(of: "\", \"", with: "")
        .replacingOccurrences(of: "\"]", with: "")
    // 转义尖括号
    let escapedHTML = rawHTML
        .replacingOccurrences(of: "<", with: "&lt;")
        .replacingOccurrences(of: ">", with: "&gt;")
}

内容的提问来源于stack exchange,提问作者Jessica Kimble

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:25:04