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.
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:
Lets elaborate on what is going on here:
- The first parameter of.
replace()is regular expression
- Regular expressions are essentially rules used to define a set of characters to match and to subsequently invoke the replace method on.
- To remove
]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.