![](/img/trans.png)
[英]Remove square brackets at beginning and ending using Undersore or Javascript
[英]Remove square brackets at beginning and ending of string
我想从字符串的开头和结尾删除方括号,如果它们存在的话。
[Just a string]
Just a string
Just a string [comment]
[Just a string [comment]]
应该导致
Just a string
Just a string
Just a string [comment]
Just a string [comment]
我试图建立一个正则表达式,但我没有以正确的方式得到它,因为它不寻找位置:
string.replace(/[\[\]]+/g,'')
string.replace(/^\[(.+)\]$/,'$1')
应该做的伎俩。
^
匹配字符串的开头 $
匹配字符串的结尾。 (.+)
匹配其间的所有内容,并在最终字符串中将其报告回来。 可能是一个更好的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); });
Blue112提供了解决方案,以除去[
和]
从行的开头/结束(如果两者都存在的话)。
要从字符串的开头/结尾删除[
和]
(如果两者都存在),则需要
input.replace(/^\[([\s\S]*)]$/,'$1')
要么
input.replace(/^\[([^]*)]$/,'$1')
在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.