【问题标题】:Return the first two string with a matching keyword返回具有匹配关键字的前两个字符串
【发布时间】:2017-05-09 22:06:45
【问题描述】:

我得到返回的聚合列表,它是一个字符串。我只想显示两个项目并删除其余项目。希望在 javascript 中执行此操作。

我有一些看起来像这样的东西:

"type:of:pets:pet:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993"

我想把前两只宠物还回去,把剩下的剥掉:

"type:of:pets:pet:304126008:pet:328464062"

我试图做类似的事情:

var types = "type:of:pets:pet:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993"

types.split('type:of:pets:pet', 2);

看起来它也没有考虑到我需要的数字。

【问题讨论】:

标签: javascript arrays sorting arraylist


【解决方案1】:

您可以对 7 个单词进行切片,这样就可以保留 3 个开头的单词和 2 个后面的单词对。

const types = "type:of:pets:pet:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993";

const r = types.split(':').slice(0, 7).join(':');

console.log(r)

如果需要 es5 兼容性,请将 const 交换为 var

【讨论】:

    【解决方案2】:

    const input = 'type:of:pets:pet:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993';
    
    const start = 'type:of:pets';
    const petDelimiter = ':pet:';
    const pets = input.substr(start.length + petDelimiter.length).split(petDelimiter);
    const result = start + pets.slice(0, 2).map(pet => petDelimiter + pet).join('');
    
    console.log(result)

    【讨论】:

      【解决方案3】:

      使用正则表达式:

          var pets = "type:of:pets:pet:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993".match(/(pet:[0-9]+)/g);
          console.log("type:of:pets:" + pets.slice(0, 2).join(":"));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多