删除字符串开头和结尾的方括号

use*_*695 7 javascript regex

我想从字符串的开头和结尾删除方括号,如果它们存在的话.

[Just a string]
Just a string
Just a string [comment]
[Just a string [comment]]
Run Code Online (Sandbox Code Playgroud)

应该导致

Just a string
Just a string
Just a string [comment]
Just a string [comment]
Run Code Online (Sandbox Code Playgroud)

我试图建立一个正则表达式,但我没有以正确的方式得到它,因为它不寻找位置:

string.replace(/[\[\]]+/g,'')
Run Code Online (Sandbox Code Playgroud)

blu*_*112 9

string.replace(/^\[(.+)\]$/,'$1')
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.

  • ^ 匹配字符串的开头
  • $ 匹配字符串的结尾.
  • (.+) 匹配其间的所有内容,在最终字符串中报告.

  • OP不想构建一个括号匹配器,只是一个正则表达式,如果两者都存在,则删除最终和第一个括号.请不要过度假设. (8认同)
  • @Cerbrus我们只有OP给我们的问题定义.在对这个问题的评论中,他们已经说过,无论如何,这些输入都是无效的. (2认同)