Reputation: 55333
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`
Upvotes: 0
Views: 45
Reputation: 371193
I'd use .reduce
instead - on each iteration, carry out the replacement on the accumulator, and return the new replaced string:
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: ''
}]
const multiReplace = (contents, regexes) => regexes.reduce(
(str, { pattern, replacement }) => str.replace(pattern, replacement),
contents
);
console.log(multiReplace(contents, regexes))
Upvotes: 2