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

Javascript 返回带有匹配关键字的前两个字符串,javascript,arrays,sorting,arraylist,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 = "typ

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

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

您可以将7个单词切分,这样您就可以保留3个第一个单词和2对后续单词

const types=“类型:of:pets:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993”;
const r=types.split(':').slice(0,7).join(':');
console.log(r)
const input='type:of:pets:pet:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993';
const start='类型:of:pets';
常量petDelimiter=':pet:';
常量pets=input.substr(start.length+petDelimiter.length).split(petDelimiter);
const result=start+pets.slice(0,2).map(pet=>petDelimiter+pet.join(“”);
console.log(结果)
使用正则表达式:

var pets=“类型:of:pets:304126008:pet:328464062:pet:329003654:pet:274825265:pet:302508993”。匹配(/(pet:[0-9]+)/g);

log(“类型:of:pets:+pets.slice(0,2.join)(:”))你尝试了什么?你有代码要显示吗?