简体   繁体   中英

How to check if a string contains a substring from an array and split it

I have an array of string like:

var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]

and I want to check if in my string (eg var myString= "Cod.Fisc.FGDTFR34L16G643W" ) exists that substring (in this case "Cod.Fisc"). If I found the substring I want to split my string in two parts like ["Cod.Fisc", "FGDTFR34L16G643W"] . How can I do that using JavaScript?

You could find the string and take the rest. Maybe it is better to sort the pattern array by length descending, because it finds the longest string first.

 var matchCodFisc = ["CF", "CF", "Cod.Fisc.", "CF"], 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); 

You can use find, includes and split

  • First find the matching value from matchChodFisc using find and includes
  • Create a regex pattern based on value of found
  • Split using regex we built and fillter empty values

 var matchCodFisc = ["CF", "CF", "Cod.Fisc.", "CF"] var myString= "Cod.Fisc.FGDTFR34L16G643W" let found = matchCodFisc.find(val=> myString.includes(val)) let regex = new RegExp(`(${found})`, 'gi') let splited = myString.split(regex).filter(Boolean) console.log(splited) 

You could do with Array#findIndex method using Str.includes()

 var matchCodFisc = ["CF", "CF", "Cod.Fisc.", "CF"] var myString = "Cod.Fisc.FGDTFR34L16G643W"; var resindex = matchCodFisc.findIndex(a => myString.includes(a)); console.log([ matchCodFisc[resindex], myString.split(matchCodFisc[resindex])[1] ]) 

Make your array into a regular expression:

 const matchCodFisc = ["CF", "CF", "Cod.Fisc.", "CF"]; const myString = "Cod.Fisc.FGDTFR34L16G643W"; const splitRegex = new RegExp('('+matchCodFisc.join('|')+')\\\\w+', 'g'); console.log(splitRegex); let result = splitRegex.exec(myString) console.log(result[1]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM