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?
2
Answers
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
exclude
and the array to apply the regex to each line.A function to remove the whole line in
str
that are listed in theexclude
array: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 functionremoveWhitespace
is necessary to remove whitespaces caused when entering the string between backticks, and also removing the whitespaces in the resulting array.@Yogi,
adding a
trim()
to remove the extra whitespace at the top of the resulting string.Result:
I tried also to replace the regex to something that could be defined outside the function but I was unsuccessful. Something like: