返回带有匹配关键字的前两个字符串

时间:2017-05-09 22:06:46

标签: javascript arrays sorting arraylist

我得到了返回和聚合列表,这是一个字符串。我只想显示两个项目并删除其余项目。希望在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);

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)



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)




答案 2 :(得分:0)

使用正则表达式:



    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(":"));