javascript - 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))
解决方案
' 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 方法中使用函数。
推荐阅读
- android - Android 的 WebViewClient.shouldInterceptRequest() 仅在第一次调用
- javascript - 在 IE 11 中抑制 Active X 警告“此页面上的 Active X 控件”
- python - 从 Pandas 数据框中的列表中创建元组列表
- c# - 在 .Net Core 中上传图片 为什么这段代码不起作用?
- java - 如何获取 Arraylist 的名称 Java
- rust - 是否可以从文件创建流而不是将文件内容加载到内存中?
- sql - 为什么我的更新查询将不正确的信息传递给表?
- javascript - 如何在 Vue.js 中将 router.push 用于相同的路径、不同的查询参数
- c++ - 读取一组用户输入,升序排序,打印结果
- javascript - 与文件交互的最佳实践 (Javascript)