在数组中查找匹配的字符串并重新编写该数组

时间:2016-01-22 20:15:39

标签: javascript arrays string

我需要你的帮助。

我希望能够在数组中找到一个字符串,并根据是否找到该值,以便能够相应地调整数组。

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"]

现在有些处理......

If ("BNI to" matches what is in the array temp then) {

    Find the instance of "BNI to" and re-label to single name: Briefing Notes (Info)
}

If ("BNA to" matches what is in the array temp then) {

    Find the instance of "BNA to" and re-label to single name: Briefing Notes (Approval)

}

重写并输出相同的临时数组,现在读作:

var temp = ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"]

4 个答案:

答案 0 :(得分:1)

执行map - 替换您需要的内容 - 然后运行reduce以删除重复内容:

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"];

var formatted = temp.map(function(str) {
    //Replace strings
    if (str.indexOf("BNI to") > -1) {
        return "Briefing Notes (Info)"
    } else if (str.indexOf("BNA to") > -1) {
        return "Briefing Notes (Approval)";
    } else {
        return str;
    }
}).reduce(function(p, c, i, a) {
    //Filter duplicates
    if (p.indexOf(c) === -1) {
        p.push(c);
    }
    return p;
}, []);

//Output: ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"]

答案 1 :(得分:0)

一些map和一个replace应该可以解决问题

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"];
var result = temp.map(function(str) {return str.replace(/BNI/i, 'Briefing Notes (Info)');}).map(function(str) {return str.replace(/BNA/i, 'Briefing Notes (Approval)');});
console.log(result);

答案 2 :(得分:0)

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"];
temp.forEach(function(v, i) {
  temp[i] = v.replace(/^BNI to/, 'Briefing Notes (Info)')
             .replace(/^BNA to/, 'Briefing Notes (Approval)');
})

答案 3 :(得分:0)

 $(document).ready(function () {
        var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"];


        var BNIRegex = new RegExp("BNI to");
        var BNARegex = new RegExp("BNA to");

        var BNISubstituteString = "Briefing Notes (Info)";
        var BNASubstituteString = "Briefing Notes (Approval)";

        for (i = 0; i < temp.length; i++) {
            temp[i] = temp[i].replace(BNIRegex, BNISubstituteString);
            temp[i] = temp[i].replace(BNARegex, BNASubstituteString);
            alert(temp[i]);
        }

    });