0

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`
3
  • What is the content of result array? Commented May 28, 2021 at 5:00
  • 1
    If you always replace it with "", you could create an alternation with | like this: /<!--[\s\S]*?-->|\n\n{2,}/ Commented May 28, 2021 at 5:04
  • .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 a forEach or reduce or a regular loop to get a single result. Commented May 28, 2021 at 5:05

1 Answer 1

2

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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.