I think this would do it:
names = thisComp.layer("A").text.sourceText.replace("\u200B","").split(","); // this makes it an Array, (after removing any invisible spaces)
word = thisComp.layer("B").text.sourceText.value;
regex = new RegExp(word, "gi"); // ,"i" makes it a case insensitive search
if (word.length > 1) {
names
.filter(a => a.match(regex)) // only array elements that match the word
.map(a => a.trim().replace(regex, "\u200B$&\u200B")) // trim extra whitespace, then surround the found queries with invisible spaces
.sort( (a,b) => a.toLowerCase().indexOf(word.toLowerCase()) - b.toLowerCase().indexOf(word.toLowerCase()))
.join("\r"); // turns the array into a string
} else {
"";
}
It sorts by where in the name the substring is found, and for equal positions, should retain the alphabetical sorting that was already in place.
all the toLowerCase() makes it a bit messy, but that’s to make that part of the code case insensitive too. Could be done with a regular expression too perhaps.