JavaScript如何用正则拆分字符串为参数且不破坏引号内容
你可以通过正则匹配替代split拆分来实现需求,核心是优先匹配被引号包裹的内容,再匹配普通无空格的字符,最后统一去除包裹的引号即可。如果你的输入字符串里的引号是"格式的HTML实体,先做一步实体转义再处理即可,实现代码如下:
const content = 'this is a simple text that i "need to split into" arguments' // 先转义HTML引号实体 const decodedContent = content.replace(/"/g, '"') // 正则优先匹配双引号包裹的内容,再匹配不含空格、引号的连续字符 const args = decodedContent.match(/(".*?"|[^"\s]+)/g) // 去除每个元素首尾的引号标记 .map(str => str.replace(/^"(.+)"$/, '$1')) console.log(args) // 输出:['this', 'is', 'a', 'simple', 'text', 'that', 'i', 'need to split into', 'arguments']
如果需要兼容单引号包裹的场景,调整正则即可:
// 同时支持单、双引号包裹 const args = decodedContent.match(/(['"]).*?\1|[^'"\s]+/g) .map(str => str.replace(/^(['"])(.+)\1$/, '$2'))
如果需要支持引号内的转义引号(比如"content with \"escaped quotes\""),可以使用支持转义判断的正则版本:
const args = decodedContent.match(/(?<!\\)"((?:\\"|[^"])*)(?<!\\)"|[^"\s]+/g) .map(str => str.replace(/^"(.+)"$/, '$1').replace(/\\"/g, '"'))
内容的提问来源于stack exchange,提问作者Sasuke
相关产品推荐
相关产品推荐

