如何在保留边界字符的同时拆分字符串?
How to split a string while retaining the boundary characters?
我正在尝试拆分 Javascript 中的字符串(使用半 json 对象)以在 }, {
上拆分,同时我想保留大括号,为此我认为使用 zerowidth lookback 和 zerowidth lookforward 作为 described here
"{}, {a}, {c:d}".split(/(?<=}), ?(?={)/)
在 chrome 中,这按预期工作,并生成一个包含三个字符串元素的数组,在开始和结束处都带有花括号,但是在 Safari 和 Firefox 中,这失败了,因为没有实现 lookbehind regex 是否有一个很好的用拆分保留花括号的方法?我试过了:
"{}, {a}, {c:d}".split(/(}), ?({)/)
但这会拆分每个字符。
您可以使用 string.split(/}, ?(?={)/)
(其中 (?<=})
正后视转换为消费 }
),然后将 }
附加到结果数组中的每个项目 other比上一个.
var string = "{}, {a}, {c:d}";
var items = string.split(/}, ?(?={)/);
var result = items.map(function(x,id,arr) {
return x + (id != arr.length - 1 ? "}" : "");
});
console.log(result);
我正在尝试拆分 Javascript 中的字符串(使用半 json 对象)以在 }, {
上拆分,同时我想保留大括号,为此我认为使用 zerowidth lookback 和 zerowidth lookforward 作为 described here
"{}, {a}, {c:d}".split(/(?<=}), ?(?={)/)
在 chrome 中,这按预期工作,并生成一个包含三个字符串元素的数组,在开始和结束处都带有花括号,但是在 Safari 和 Firefox 中,这失败了,因为没有实现 lookbehind regex 是否有一个很好的用拆分保留花括号的方法?我试过了:
"{}, {a}, {c:d}".split(/(}), ?({)/)
但这会拆分每个字符。
您可以使用 string.split(/}, ?(?={)/)
(其中 (?<=})
正后视转换为消费 }
),然后将 }
附加到结果数组中的每个项目 other比上一个.
var string = "{}, {a}, {c:d}";
var items = string.split(/}, ?(?={)/);
var result = items.map(function(x,id,arr) {
return x + (id != arr.length - 1 ? "}" : "");
});
console.log(result);