如何移除模板字符串中的空字符串以消除多余换行?
解决方案
方法1:将条件块的缩进/换行纳入三元判断
问题根源是你只把条件内容放进了三元表达式,但周围的缩进和换行仍留在模板里。把包含缩进、换行和内容的完整片段都放进三元的true分支,这样数据不存在时,整块的空白和内容都不会输出:
arrayOfObjects.map(a => { return ` ; ...other code that doesn't depend on data ; Code that depends on data, if it's false I want to remove it completely and ; and avoid passing empty string as it creates extra space in the generated file ${a.stripe_connected_account ? ` [[:im.stripeAccount/id] #:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}" :user #im/ref :user/${a.user}}]` : ''} `; });
注意看,原本模板里的缩进和换行被移到了三元的true分支内,条件不满足时只会插入空字符串,不会带出多余的空白。
方法2:用数组收集有效片段再拼接
如果有大量这类条件块,用数组收集需要输出的内容会更清晰,从根源避免空字符串带来的问题:
arrayOfObjects.map(a => { const lines = [ ' ; ...other code that doesn\'t depend on data', '', ' ; Code that depends on data, if it\'s false I want to remove it completely and', ' ; and avoid passing empty string as it creates extra space in the generated file' ]; // 仅当数据存在时,才将对应EDN片段加入数组 if (a.stripe_connected_account) { lines.push(` [[:im.stripeAccount/id] #:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}" :user #im/ref :user/${a.user}}]`); } // 拼接所有有效内容 return lines.join('\n'); });
这种方式逻辑直观,所有输出内容都明确加入数组,空场景直接跳过,不会产生冗余空白。
方法3:生成后清理多余空白(兜底方案)
如果前两种方式不好调整,也可以在生成最终字符串后,用正则清理多余空行和连续空白:
const generatedEdn = arrayOfObjects.map(a => { return ` ; ...other code that doesn't depend on data ; Code that depends on data, if it's false I want to remove it completely and ; and avoid passing empty string as it creates extra space in the generated file ${a.stripe_connected_account ? `[[:im.stripeAccount/id] #:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}" :user #im/ref :user/${a.user}}]` : ''} `; }).join('\n'); // 清理多余空行和不必要的连续缩进 const cleanedEdn = generatedEdn.replace(/^\s*\n/gm, '').replace(/\s{2,}/g, ' ');
注意正则匹配规则,避免误删EDN语法要求的必要空白。
内容的提问来源于stack exchange,提问作者Aleksa
相关产品推荐
相关产品推荐

