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,'')
3 个解决方案
#1
8
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.
^匹配字符串的开头
$匹配字符串的结尾。
(。+)匹配中间的所有内容,在最终字符串中报告。
#2
0
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
#3
0
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"));
#1
8
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.
^匹配字符串的开头
$匹配字符串的结尾。
(。+)匹配中间的所有内容,在最终字符串中报告。
#2
0
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
#3
0
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"));