我在Zapier中大量使用自定义JS代码。将数组导入此步骤时,Zapier会将其转换为文字字符串,即:
'BigBoatBob,XL-1','LittleBoatMike,M-2','SunkBoatCheney,XS-9‘
变成:
'BigBoatBob、XL-1、LittleBoatMike、M-2、SunkBoatCheney、XS-9‘
我已经创建了一个函数来解析数组项(考虑到文本逗号),但它看起来非常、非常草率。有没有人有什么建议可以改进/缩短/使看起来更专业?感谢您帮助我进一步提高我的能力:)
var array = splitArray('BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9');
function splitArray(x) {
const pos = [];
const POS = [];
const res = [];
for (var i = 0; i < x.length; i++) {
if (x[i] == ',') pos.push(i);
}
for (i = 0; i < pos.length; i++) {
let a = x.slice(pos[i]);
if (!a.startsWith(', ')) POS.push(pos[i]);
}
POS.push(x.length);
POS.unshift(0);
for (i = 0; i < POS.length - 1; i++) {
res.push(x.slice(POS[i], POS[i+1]));
}
return res.map(x => {
if (x.startsWith(',')) {
return x.slice(1);
} else {
return x;
}
});
}
console.log(array);发布于 2019-10-26 22:00:06
如果您可以依赖字符串中逗号后面的空格和字符串之间的空格,则可以将split与正则表达式/,(?! )/一起使用,该正则表达式表示"a comma 后面跟一个空格:“
const str = 'BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9';
const array = str.split(/,(?! )/);
console.log(array);
如果你不能依赖它,但是你可以依赖XL-1的格式,你可以使用exec循环(或者使用最新的JavaScript引擎或者polyfill,使用matchAll):
const str = 'BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9';
const array = [];
const rex = /(.*?,\s*[A-Z]{1,2}-\d)\s*,?/g;
let match;
while ((match = rex.exec(str)) !== null) {
array.push(match[1]);
}
console.log(array);
正则表达式/(.*?,\s*[A-Z]{1,2}-\d)\s*,?/g表示:
捕获任意数量的任意字符,捕获comma
\s*零个或多个空格characters
[A-Z]{1,2}范围中的一个或两个字母A-Z
- a dash
\d a single digit (如果可以有多个,请使用\d+ )
发布于 2019-10-26 22:09:02
我会使用Array.reduce:
var s = 'BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9'
var result = s.split(',').reduce((acc, curr, i) => {
if(i % 2 == 0) { acc[i] = curr }
else { acc[i - 1] += curr }
return acc
}, []).filter(x => x)
console.log(result)
发布于 2019-10-26 22:26:52
速记,
function splitIt(str) {
return str.split(',').reduce((a,v,i)=>((i % 2 == 0)?a.push(v):a[a.length-1]=a[a.length-1]+","+v,a),[]);
}
// Example
let str = `BigBoatBob, XL-1,LittleBoatMike, M-2,SunkBoatCheney, XS-9`;
console.log(splitIt(str));https://stackoverflow.com/questions/58571393
复制相似问题