I have a bad word that contains illegal letters. I have a list of legal letters (which can be more than one character long). The following nested loop iterates over both the characters in the word and the legal letters, replacing any illegal letter with null
.
In order to both retain the legal letters and substitute illegal ones, it's important that all legal letters are looped through. The illegal substitution would happen once that loop finishes.
// acceptable letters:
const legalLetters = ["ND", "CH", "S"]
// bad, evil word containing unacceptable letters:
let word = "SANDWICH"
const filteredLetters = []
while (word.length > 0) {
for (const letter of legalLetters) {
if (word.startsWith(letter)) {
// remove that many letters from the start of the word
word = word.slice(letter.length)
filteredLetters.push(letter)
// break back to the while loop to re-scan the truncated word
break
}
} else {
// this is the part I'm having trouble with
// if the word does not start with an acceptable letter, remove that letter
word = word.slice(1)
filteredLetters.push(null)
}
// some filteredLetter was added and the length of the word has been reduced
// repeat until the word is all gone
}
console.log(filteredLetters) // should be ["S", null, "ND", null, null, "CH"]
In the above example I've used Python's for ... else
construct, which executes the code in the else
block only if there was no break
in the for
block. Such a syntax does not exist in Javascript (and therefore the snippet above is nonsense).
How would I go about creating this 'default behaviour' in Javascript?
Lodash and co. answers are okay for my purposes, and this may well be an XY problem, so I welcome any restructuring advice.
Related question: For else loop in Javascript?
The answers to this question recommend either setting a boolean flag or breaking to a label. I'd prefer to avoid these approaches, if possible - the flag approach feels messy, creating an unnecessary variable, and the label approach just doesn't feel quite right.