Gig*_*ove 1 javascript split match
我有一个像这样的字符串数组:
var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]
Run Code Online (Sandbox Code Playgroud)
并且我想检查我的字符串(例如var myString= "Cod.Fisc.FGDTFR34L16G643W")中是否存在该子字符串(在这种情况下为“ Cod.Fisc”)。如果找到子字符串,我想将字符串分成两部分,例如["Cod.Fisc", "FGDTFR34L16G643W"]。如何使用JavaScript做到这一点?
您可以找到该字符串,然后取走其余的字符串。也许最好按长度降序对模式数组进行排序,因为它会先找到最长的字符串。
var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"],
string = "Cod.Fisc.FGDTFR34L16G643W",
found = matchCodFisc
.sort((a, b) => b.length - a.length)
.find(s => string.startsWith(s)),
result = [found, string.slice(found.length)];
console.log(result);Run Code Online (Sandbox Code Playgroud)