I want to match and store string in an array using javascript and need regular expression for this. Other solution also appreciated. separated by '_' if only both matches in string those string from array should be retured only, no other match should be accepted. Array and search string both are dynamic. Below is just an example but solution shoud match for any dynamic data. Example problem given below.
let arr1 = ['ef','cd','ab','cdab','efab','cdef','ab/cd/ef','cd/ef,ab','cd/ab','ab/ef']
test scenarios:
- let search = 'ef_ab'; expected output would be ['efab','ab/ef']
- let search = 'ab_cd_ef'; expected output would be ['ab/cd/ef','cd/ef,ab']
- let search = 'cd'; expected output would be ['cd']
Any help in javascript for problem is appreciated.
I have tried below regex and looping. Here word1 for given example could be ab or cd or ef and same could be for word2 , word3
let arr1 = ['ef', 'cd', 'ab', 'cdab', 'efab', 'cdef', 'ab/cd/ef', 'cd/ef,ab', 'cd/ab', 'ab/ef']
let regex = /(?=.*word1)(?=.*word2)(?=.*word3)/;
let arr2 = [];
for (i = 0; i < arr1.length; i++) {
if (regex.test(arr1[i]))
arr2.push(arr1[i]);
}
console.log(arr2)