简体   繁体   English

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

[英]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,'')
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. (.+)匹配其间的所有内容,并在最终字符串中将其报告回来。

Probably a better reg exp to do it, but a basic one would be: 可能是一个更好的reg exp来做,但一个基本的将是:

 var strs = [ "[Just a string]", "Just a string", "Just a string [comment]", "[Just a string [comment]]" ]; var re = /^\\[(.+)\\]$/; strs.forEach( function (str) { var updated = str.replace(re,"$1"); console.log(updated); }); 

Reg Exp Visualizer Reg Exp Visualizer

Blue112 provided a solution to remove [ and ] from the beginning/end of a line (if both are present). Blue112提供了解决方案,以除去[]的开头/结束(如果两者都存在的话)。

To remove [ and ] from start/end of a string (if both are present) you need 要从字符串的开头/结尾删除[] (如果两者都存在),则需要

input.replace(/^\[([\s\S]*)]$/,'$1')

or 要么

input.replace(/^\[([^]*)]$/,'$1')

In JS, to match any symbol including a newline, you either use [\\s\\S] (or [\\w\\W] or [\\d\\D] ), or [^] that matches any non-nothing . 在JS中,要匹配包含换行符的任何符号,您可以使用[\\s\\S] (或[\\w\\W][\\d\\D] )或[^]匹配任何空格。

 var s = "[word \\n[line]]"; console.log(s.replace(/^\\[([\\s\\S]*)]$/, "$1")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM