I found myself using a lot of .replace.replace. So I decided to create a function that receives regexes as argument and uses them to replace substrings inside a string. I wanted to return a value, so I decide to use map instead of forEach:
const contents = `"Some text"
<!-- Some comment-->
More text`
const HTMLCommentsRegex = /<!--[\s\S]*?-->/g
const multipleLinesRegex = /\n\n{2,}/g
const regexes = [{
pattern: HTMLCommentsRegex,
replacement: ''
}, {
pattern: multipleLinesRegex,
replacement: ''
}]
console.log(multiReplace(contents, regexes))
function multiReplace(contents, regexes) {
const result = regexes.map((regex) => {
return contents.replace(regex.pattern, regex.replacement)
})
return result
}
But I immediately realized my error. I'm returning an array instead of a string (like the original content of contents).
How to modify this code so that the function returns a string instead?
Desired output (basically removing HTML comments and multiple empty lines):
const contents = `"Some text"
More text`
"", you could create an alternation with|like this:/<!--[\s\S]*?-->|\n\n{2,}/.map()creates a new array from the current one by passing each of the current elements through a mapping function. So, it's a the result is 1:1 with the input. You need aforEachorreduceor a regular loop to get a single result.