Suppose, I've a string -
"abcfile.csv"
& an array of strings -
[“abc.csv”、“abcf.csv”、“cde.doc”、“abcdefile.csv”、“abcfi.csv”]
在这里,我想将给定的字符串“abcfile.csv”与字符串数组部分匹配,它应该给我数组中的一个元素作为输出,其中最多。连续字符匹配。。
That is, in this example, It should return "abcfi.csv" from the array as it has the more no. of matching consecutive characters with "abcfile.csv".
我尝试了一些字符串相等方法,但没有帮助。 (包括
、===
等)。
更新:
<小时/>我正在尝试将 @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”
最佳答案
您应该使用 while
循环并检查是否存在包含所需字符串的数组项。
每次迭代后,您应该切片
不带最后一个字符的字符串等等。
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);
关于javascript - 从数组中获取最合适的匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132095/