Remove Brackets and Text Inside Them Using Regex Without Extra Remaining Spaces

Viewed 42

I want to remove the [] signs and whatever inside them in the given string:

const text = "This should [but this should be removed with the brackets] stay intact."

const result = text.replace(/\[.*?\]/g,'')

console.log(result);

The issue is the extra space remain after the removal of brackets.

How can I fix this?

2 Answers

I'd optionally match spaces on either side of the pattern, then replace with a single space:

const text = "This should [but this should be removed with the brackets] stay intact."

const result = text.replace(/ ?\[[^\]]*\] ?/g,' ')

console.log(result);

Split with regex that matches whitespaces on both ends, and join:

const text = "This should [but this should be removed with the brackets] stay intact."
const result = text.split(/\s*\[[^\][]*]\s*/g).join(" ");
console.log(result)

Result: This should stay intact.

Expression explanation:

--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \[                       '['
--------------------------------------------------------------------------------
  [^\][]*                  any character except: '\]', '[' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  ]                        ']'
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
Related