2016-02-11 48 views
1

我试图通过寻找关键字数组进行互动,并拆分其包含它们分成两个或更多个键,其中包含与年初的关键字和其他(S)的关键,一个和之前的结局。独立的JavaScript数组由唯一关键字

例如,假设我有关键字 “猫” 和 “狗”

var arrayinput = ["acat", "zdogg", "dogs"];

的desidered输出将

[ "a", "cat", "z", "dog", "g", "dog", "s" ]

我一直在制造含有常规表达式我的关键字模式和使用.match()

然而,像“ACAT”将返回一个有效的匹配关键字“猫”。鉴于“acat”,我需要“a”分开看,然后“猫”被视为有效。

+0

当你匹配,你需要使用不印字/拼接的元素添加到数组索引。 –

回答

2

检查在这里:https://jsfiddle.net/3jtqc2s2/

arrayinput = [].concat.apply([], arrayinput.map(function (v) { 
    return v.split(/(cat|dog)/); 
})).filter(function(v) { 
return v !== ""; 
}); 

这也将检测多的猫或狗的术语。

0

解决方案与Array.forEachString.match功能:

var arrayinput = ["acat","zdogg","dogs"], 
    result = [], 
    matches; 

    arrayinput.forEach(function(word){ 
     matches = word.match(/^(\w*)(cat|dog)+(\w*)$/i); 
     if (matches[1]) result.push(matches[1]); 
     if (matches[2]) result.push(matches[2]); 
     if (matches[3]) result.push(matches[3]); 

    }); 

    console.log(result); 
    // the output: 
    ["a", "cat", "z", "dog", "g", "dog", "s"] 
0

使用标准for循环的另一个解决方案:

var result = []; 
    for(var currentValue of arrayinput) { 
     var obj = currentValue.split(/(cat|dog)/); 
     result = result.concat(obj.filter(function(v) {return v != '';})); 
    } 
0

三使用强制为字符串时,正则表达式替换,和胁迫回阵列相关的解决方案。没有使用循环。不要说这是优雅,高效或推荐的,只是这是可能的。

var arrayinput = ["acat", "zdogg", "dogs"]; 
 

 
document.write(
 
    arrayinput 
 
    .join(" ")       // coerce to space-separated string 
 
    .replace(/(cat|dog)/g, " $1 ")  // flank all keywords with spaces 
 
    .replace(/ +/g, " ")     // collapse multiple spaces to one 
 
    .trim()        // remove leading or trailing spaces 
 
    .split(" ")       // re-create array, splitting at spaces 
 
); 
 

 
document.write("<br />"); 
 

 
document.write(
 
    arrayinput 
 
    .join(" ")       // coerce to space-separated string 
 
    .replace(/\B(cat|dog)/g, " $1")  // precede embedded keyword-starts with spaces 
 
    .replace(/(cat|dog)\B/g, "$1 ")  // follow embedded keyword-ends with spaces 
 
    .split(" ")       // re-create array, splitting at spaces 
 
); 
 

 
document.write("<br />"); 
 

 
document.write(
 
    arrayinput 
 
    .toString()       // coerce to comma-separated string 
 
    .replace(/([^,])(cat|dog)/g, "$1,$2") // precede embedded keyword-starts with commas 
 
    .replace(/(cat|dog)([^,])/g, "$1,$2") // trail embedded keyword-ends with commas 
 
    .split()        // re-create array, splitting at commas 
 
);