let text = "docker run -d -p 8080:8080 -p 8081:8081 -p 8081:8081 -p 8081:8081 -P 8082 -P 8082 -e key1=value1 -e key2=value23 -e key3 value3" let array1 = findStringIndex(text, " -p "); let array2 = findStringIndex(text, " -P "); let array3 = findStringIndex(text, " -e "); function findStringIndex(text1, text2) { let array = []; let index = text1.indexOf(text2); while (index !== -1) { array.push(index); index = text1.indexOf(text2, index + 1); } return array; }