假设我有一个字符串 -
"abcfile.csv"
&字符串数组 -
["abc.csv", "abcf.csv", "cde.doc", "abcdefile.csv", "abcfi.csv"]
在这里,我希望将给定的字符串"abcfile.csv"
与字符串数组部分匹配,它应该从数组中给出一个元素作为输出,其中最多。连续字符匹配。。
也就是说,在这个例子中,它应该从数组中返回“abcfi.csv”,因为它有更多的no。匹配连续字符与“abcfile.csv”。
我尝试了一些字符串相等的方法,但它没有帮助。 (includes
,===
等)。
更新
我正在尝试将 @ Alexandru-Ionut Mihai 提供的解决方案应用于我的实际数据,但是遇到了一些情况 -
let arrayFiles = ["Account_Summary_(LS)_Mar'17.csv", "Additions and Changes_MACD (LS)_Mar'17.csv", "Adjustment and Payments_Mar'17.csv", "CDR LD.csv", "CDR's_-_All_(LS)_Mar'17.csv", "CSR.csv", "Customer_Service_Records_(LS)_Mar'17.csv", "Discounts, Promotions and Fees (LS)_Mar'17.csv", "Equipment Other Charges (LD)_Mar'17.csv", "Inventory Circuits (LD)_Mar'17.csv", "Local Usage Detail (LS)_Mar'17.csv", "Other_Carrier_Detail_(LS)_Mar'17.csv", "Service Summary (LD)_Mar'17.csv", "Tax Detail (LD)_Mar'17.csv", "Tax_Detail_(LS)_Mar'17.csv"];
let arrayTable = ["CSR.csv", "Tax Detail LD.csv", "Tax Detail LS.csv", "Additions and Changes MACD LS.csv", "Adjustment and Payments.csv", "CDR LS.csv", "CDR LD.csv", "Discounts Promotions and Fees LS.csv", "Equipment Other Charges LD.csv", "Inventory Circuits LD.csv", "Local Usage Detail LS.csv", "Other Carrier Detail LS.csv", "Audio Conference.csv", "Toll Free.csv", "Other Charges.csv", "Account Statement.pdf", "Extended Area service.csv", "Local Message Services.csv", "Report - Charges by Line taxes.csv", "Billing Adjustments.csv", "Usage Details.csv", "Account Statement.pdf"];
let string = arrayFiles[11]; // "Other_Carrier_Detail_(LS)_Mar'17.csv"
let found;
while (string.length > 0) {
let elem = arrayTable.find(a => a.includes(string));
if (elem) {
found = elem;
break;
}
string = string.slice(0, -1);
}
console.log(found);
在这里,我希望它返回arrayTable [12],即“其他载波明细LS.csv”,但它返回“设备其他费用LD.csv”
答案 0 :(得分:2)
您应该使用while
循环并检查是否存在包含所需字符串的数组项。
每次迭代后,你应该slice
没有最后一个字符串的字符串,依此类推......
abcfile.csv -> abcfile.cs -> abcfile.c -> abcfile. -> abcfile -> abcfil -> abcfi -> abcf -> abc -> ab -> a ->""
使用此方法,您将从数组中找到最合适的匹配字符串。
let string = "abcfile.csv";
let array = ["abc.csv", "abcf.csv", "cde.doc", "abcdefile.csv", "abcfi.csv"];
let found;
while(string.length > 0){
let elem = array.find(a => a.includes(string));
if(elem){
found = elem;
break;
}
string = string.slice(0,-1);
}
console.log(found);