js 去掉字符串中首尾的括号

282 阅读1分钟
function removeOuterBrackets(str) {
  return str.replace(/^\[|\]$/g, '');
}
 
// 示例使用
const str1 = "[Hello]";
const str2 = "[[Hello]]";
const str3 = "[[[Hello]]]";
 
console.log(removeOuterBrackets(str1)); // 输出: Hello
console.log(removeOuterBrackets(str2)); // 输出: Hello
console.log(removeOuterBrackets(str3)); // 输出: Hello

这个函数使用了正则表达式中的^来匹配字符串开头,$来匹配字符串结尾,|表示逻辑或,]匹配字面上的方括号。这样就能确保只有在字符串的开头和结尾处的方括号被移除。如果字符串中间有方括号,它们不会被移除。