You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何按完整块分割含转义换行符的字符串?

解决方案

直接使用正则表达式的match方法,匹配所有以{开头、}结尾的完整块,就能得到你想要的结果:

const str = `{FOO: "Hello\nWorld"}
{"BAR": "Nice\nTo\nMeet\nYou"}`;

const result = str.match(/{[^}]+}/g);
console.log(result);

执行后输出:

Array(2) [ '{FOO: "Hello\nWorld"}', '{"BAR": "Nice\nTo\nMeet\nYou"}' ]

原理说明

  • 正则/{[^}]+}/g的含义:
    • {:匹配开头的左大括号
    • [^}]+:匹配任意数量不是右大括号的字符(包括换行符\n)
    • }:匹配结尾的右大括号
    • g:全局匹配,找出所有符合条件的块

这样就能精准跳过字符串内部的换行符,只把每个完整的大括号包裹块作为数组元素。

内容的提问来源于stack exchange,提问作者Alex Mortez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:40:29