JavaScript如何仅按外层大括号拆分字符串(忽略嵌套括号)
按外层大括号拆分字符串(忽略嵌套大括号)
问题分析
你的代码核心问题在于拆分时机错误:仅在遇到外层闭合大括号}时才将内容存入结果,导致普通文本(如hello )会和后续的大括号内容(如{world})合并在同一个current中,无法拆分出单独的普通文本项。此外,跳过空格的逻辑属于冗余处理,空格本身不需要特殊跳过。
修正后的代码
function splitByOuterBraces(str) { const result = []; let current = ''; let stack = 0; for (let i = 0; i < str.length; i++) { const ch = str[i]; // 遇到外层开括号时,先存入之前的普通文本 if (ch === '{' && stack === 0) { if (current) { result.push(current); current = ''; } stack++; current += ch; continue; } // 遇到外层闭括号时,存入整个大括号内容 if (ch === '}' && stack === 1) { current += ch; result.push(current); current = ''; stack--; continue; } // 处理嵌套大括号或普通字符 if (ch === '{') { stack++; } else if (ch === '}') { stack--; } current += ch; } // 存入最后剩余的普通文本 if (current) { result.push(current); } return result; } // 测试示例 const testStr = 'hello {world} this is some text. {split me {but not me} thanks} heaps!'; console.log(splitByOuterBraces(testStr)); // 输出:["hello ", "{world}", " this is some text. ", "{split me {but not me} thanks}", " heaps!"]
关键修改点
- 拆分普通文本:当遇到外层
{(栈计数为0时),先将之前收集的普通文本存入结果,再开始收集大括号内容。 - 处理外层闭合:当遇到外层
}(栈计数为1时),将整个大括号内容存入结果,然后清空current并调整栈计数。 - 保留所有字符:移除了跳过空格的逻辑,确保空格、特殊字符等所有内容都被正确收集。
- 边界处理:循环结束后检查剩余的
current,确保末尾的普通文本不会被遗漏。
内容的提问来源于stack exchange,提问作者user2052581
相关产品推荐
相关产品推荐

