I would like to remove square brackets from beginning and end of a string, if they are existing.
[Just a string]
Just a string
Just a string [comment]
[Just a string [comment]]
Should result in
Just a string
Just a string
Just a string [comment]
Just a string [comment]
I tried to build an regex, but I don't get it in a correct way, as it doesn't look for the position:
string.replace(/[\[\]]+/g,'')
Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.
Use the str. join() method to remove the square brackets from a list, e.g. result = ', '. join(str(item) for item in my_list) .
By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.
string.replace(/^\[(.+)\]$/,'$1')
should do the trick.
^
matches the begining of the string$
matches the end of the string.(.+)
matches everything in between, to report it back in the final string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With