将表达式拆分为具有多个键的数组,并在数组中包含键

时间:2017-07-10 13:32:05

标签: javascript arrays split

var expression = "[AccNum]==true&&[AccNum]==[ARID]&&[AccNum]==aaaa || [ARID]!=true&&[DOB]>[ARID] || [DOB]>bbb&&[DOS]>=[ARID]&&[DOS]<[Gender]&&[66642]<=cccc&&[66642] In (ddd,fff,ggg) || [FirstName] NotIn (hhh,jjj,kkk)&&[FirstName] StartsWith lll || [Gender] EndsWith mmm";

我需要将此表达式拆分为数组,如

var arr = [ "[AccNum]==true","&&", "[AccNum]==[ARID]", "&&", "[AccNum]==aaaa", "||", "[ARID]!=true", "&&", "[DOB]>[ARID]", "||", "[DOB]>bbb", "&&", "[DOS]>=[ARID]", "&&", "[DOS]<[Gender]", "&&", "[66642]<=cccc", "&&", "[66642] In (ddd,fff,ggg)", "||", "[FirstName] NotIn (hhh,jjj,kkk)", "&&", "[FirstName] StartsWith lll", "||", "[Gender] EndsWith mmm" ]

这里的键是"&&"和" ||"但是我也需要数组中的键。

2 个答案:

答案 0 :(得分:2)



var expression = "[AccNum]==true&&[AccNum]==[ARID]&&[AccNum]==aaaa || [ARID]!=true&&[DOB]>[ARID] || [DOB]>bbb&&[DOS]>=[ARID]&&[DOS]<[Gender]&&[66642]<=cccc&&[66642] In (ddd,fff,ggg) || [FirstName] NotIn (hhh,jjj,kkk)&&[FirstName] StartsWith lll || [Gender] EndsWith mmm";

var converted = expression
                .split(/(&&|\|\|)/)
                .map(item => item.trim());

console.log(converted)




括在括号中的RegEx分隔符将推送数组中的分隔符以及项目,这要归功于:https://stackoverflow.com/a/12002085/3499595

修剪每个项目的地图,删除空格。

答案 1 :(得分:1)

试试这个:

var expression = "[AccNum]==true&&[AccNum]==[ARID]&&[AccNum]==aaaa || [ARID]!=true&&[DOB]>[ARID] || [DOB]>bbb&&[DOS]>=[ARID]&&[DOS]<[Gender]&&[66642]<=cccc&&[66642] In (ddd,fff,ggg) || [FirstName] NotIn (hhh,jjj,kkk)&&[FirstName] StartsWith lll || [Gender] EndsWith mmm";
var splitArray = expression.split(/(&&|\|\|)/g);