首页 > 解决方案 > Javascript字符串替换正则表达式的出现比例?

问题描述

我需要减少 Javascript 中字符串的过多换行符。

目前我有以下内容:

generalsymptoms.replace(/(\s*\n\s*){6,}/g, '\n')

这将 6 个换行符替换为 1 个,但这有效地使原来的 5 个换行符比 6 个换行符有更多的间隙。

是否可以引用替换字符串中的出现,所以我可以使用类似的东西:

generalsymptoms.replace(/(\s*\n\s*){6,}/g, '\n'.repeat(number_of_occurence/2))

标签: javascriptreplace

解决方案


' a a abaaaa'.replace(/(\s*a\s*){2,}/g, (matched, index, origin)=> {console.log(matched.replace(/\s/g, '')); return 'c'})
aaa
aaaa

适用于这里

generalsymptoms.replace(/(\n\s*\n){2,}/g, matched => '\n'.repeat(matched.replace(/ /g, '').length/2)))

感谢我的前同事,他暗示我可以在 replace 方法中使用函数。


推荐阅读