How to remove brackets from string in JavaScript

When it comes to replacing characters inside strings, there is a wide range of methods that can do this job. However, sometimes we want to specifically remove certain characters from the string.

So, how can we remove brackets from a string in JavaScript? Brackets can be removed from a string in Javascript by using a regular expression in combination with the .replace() method.

For example, let’s say we have the following string:

const names = "['Tommy Vercetti','Carl Johnson']"

We can utilize .replace()  along with regex in order to remove the brackets from the string:

names.replace(/[\[\]']+/g,'')

Lets elaborate on what is going on here:

  • The first parameter of.replace() is regular expression /[\[\]']+/g.
    • Regular expressions are essentially rules used to define a set of characters to match and to subsequently invoke the replace method on.
  • To remove [. and ] individually, we need to escape them using \.
  • + applies the rule to the whole string.

And that’s pretty much it. Remember that you can create any kind of rule for matching with Regex. The possibilities are nearly endless. For testing, you can create your custom rules using this tool here.

Proudly published with Gatsby