【问题标题】:Find all ocurrences after specific string in another string在另一个字符串中查找特定字符串之后的所有匹配项
【发布时间】:2021-11-29 08:06:25
【问题描述】:

我有来自 API 的响应(实际上是来自 AWS lex 的复合消息),它看起来像这样:

 '{\"messages\":[{\"type\":\"PlainText\",\"group\":1,\"value\":\"Great!\"},{\"type\":\"PlainText\",\"group\":2,\"value\":\"Please click here.\"}]}'

我无法更改对字符串的响应,我需要从该字符串中获取以下内容:

“太好了!”“请点击这里。”

基本上在 => "value\":\"\"} 之前的任何内容

我尝试了很多方法,但都没有成功。 有什么办法可以做到这一点,我什至尝试编写一个正则表达式,但我能得到的是之前的字符串,而不是我需要的实际文本。

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    我们可以使用JSON.parse 将您的 JSON API 输出转换为 JS 对象。然后,我们可以迭代数组中的所有消息并提取值。

    var input = '{\"messages\":[{\"type\":\"PlainText\",\"group\":1,\"value\":\"Great!\"},{\"type\":\"PlainText\",\"group\":2,\"value\":\"Please click here.\"}]}';
    var x = JSON.parse(input);
    var arr = x.messages.map(item => item.value)
    console.log(arr);

    【讨论】:

    • xe 这些名字从何而来?
    • @Spectric 不错的 lambda 东西...现在正在学习。
    • 你是如何在不知道 lambdas 的情况下获得 411k 的?
    • @RoboRobok 我在 JS 中只有银牌。我的大部分代表来自 SQL、Java 和 R。好吧,我当然知道 Java 中的 lambda。
    • @Spectric 我知道,但我还是很震惊。那是一些少年JS。
    【解决方案2】:

    你为什么不直接使用JSON.parse()

    const responseJson = '{"messages":[{"type":"PlainText","group":1,"value":"Great!"},{"type":"PlainText","group":2,"value":"Please click here."}]}';
    const response = JSON.parse(responseJson);
    const values = response.messages.map(message => message.value);
    
    // values is now ['Great!', 'Please click here.']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-06
      • 2013-06-12
      • 1970-01-01
      • 2021-08-17
      • 2023-03-08
      • 2018-10-03
      • 2013-05-16
      • 2012-10-04
      相关资源
      最近更新 更多