首页 > 解决方案 > 我想在多个分隔符的基础上拆分字符串并将值和键保留在一个对象中

问题描述

示例字符串

"<#> https://firebasestorage.googleapis.com/v0/b/fabulinus-app.appspot .com/o/TestingFacts%2Fhuman-heart-health-illustration.jpg?alt= media&token=98d83908-0d84-4fb2- ac6e-4918618e2db6<#> <&>心脏是你身体循环系统的一部分。它由心房、心室、瓣膜和各种动脉和静脉组成。心脏的主要功能是保持血液中充满氧气在你的全身循环。因为你的心脏对你的生存至关重要,所以通过均衡的饮食和运动来保持它的健康很重要,并避免会损害它的东西,比如吸烟。<&> <#> https:// firebasestorage.googleapis.com/v0/b/fabulinus-app.appspot.com/o/TestingFacts%2F10- Essential-Facts-About-Heart-Failure-1440x810.jpg?alt=media&token=45e10991-065e-4e3b -b5f2-9df6f723fb5a<#> <&>您的心脏会影响您身体的每个部位。这也意味着饮食、生活方式和您的情绪健康会影响您的心脏。情绪和身体健康对于保持心脏健康都很重要。<&> <@>阅读更多:心脏健康提示<@> <#> https://firebasestorage.googleapis.com/v0/b/fabulinus-app.appspot .com/o/TestingFacts% 2Fimages%20(4).jpg?alt=media&token=275488d3-fc24-4763-9349-780593e59fe0<#>"

我想在一个对象中排列键和值

要求的结果

    [{
key : "<#>",
value:"https://firebasestorage.googleapis.com/v0/b/fabulinus-app.appspot. com/o/TestingFacts%2Fhuman-heart-health-illustration.jpg?alt= media&token=98d83908-0d84-4fb2-ac6e-4918618e2db6"
},{
key : "<&>",
value : "The heart is part of your body’s circulatory system. It’s made up of the atria, ventricles, valves, and various arteries and veins. The main function of your heart is to keep blood that’s full of oxygen circulating throughout your body. Because your heart is crucial to your survival, it’s important to keep it healthy with a well-balanced diet and exercise, and avoid things that can damage it, like smoking."
}]

我一直在尝试使用多个分隔符来拆分字符串,但我无法保留哪个键属于哪个子字符串的记录。

通过使用简单的拆分功能

split(/(<#>)/)

标签: javascript

解决方案


这是您可以开始使用的简单代码:

function tokenizer(text) {
    var regexp = /(<[#&@]>)([^<>]+)<[#&@]>/g;
    var match;
    var result = {};
    while(match = regexp.exec(text)) {
        if(!result[match[1]]) {
            result[match[1]] = [];
        }
        result[match[1]].push(match[2])
    }
    return result;
}

测试一些边缘情况。

例如当前值不能使用'<>'符号(我们使用非<>符号来检测值)。

<#>test<@> 也将被视为一个常闭标签。

但希望这会有所帮助!;)


推荐阅读