I haven't been able to find a satisfactory solution to remove lines of text that match keywords in an arrays of strings. A typical application would be, for instance, YAML frontmatter, which we want to filter of non applicable properties.
Let' say we have a string like this:
let str = `
up: some text here
archetype: "[[Atlas]]"
related:
status:
type:
uuid: '202403041152'
`
I am using backticks to enter the string to make it easier to enter one line of text at a time.
We want to exclude some properties from the frontmatter string entering the exclusions in an array.
const exclude = ["status", "type", ]
How do we remove the keywords in the array exclude from the multi-line string?
I have found the most consistent result is when we convert each line of the YAML string to an array of strings, and then iterate through
excludeand the array to apply the regex to each line.A function to remove the whole line in
strthat are listed in theexcludearray:Called with:
Output as follows:
I came up with this solution when I was receiving false positives whenever I wanted to remove
type, and unintentionally it was removing the propertyarchetype. The functionremoveWhitespaceis necessary to remove whitespaces caused when entering the string between backticks, and also removing the whitespaces in the resulting array.