Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove square brackets at beginning and ending of string

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,'')
like image 580
user3142695 Avatar asked Jul 13 '16 13:07

user3142695


People also ask

How do you remove square brackets from string?

Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.

How do I remove square brackets from a string in Python?

Use the str. join() method to remove the square brackets from a list, e.g. result = ', '. join(str(item) for item in my_list) .

What do the [] brackets mean in regular expressions?

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.


1 Answers

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.
like image 90
blue112 Avatar answered Oct 04 '22 20:10

blue112