2017-05-09 64 views
0

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

看起来它并不考虑我需要的数字。

+0

那你试试?你有任何代码要显示吗? http://stackoverflow.com/help/how-to-ask – YoannM

回答

1

您可以切分7个单词,以便保留3个第一个单词和2个以下对。如果需要ES5兼容性

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)

交换constvar

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)

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

相关问题