Reputation: 26558
I need to reduce the excessive line breaks from a string in Javascript.
Currently I have the following:
generalsymptoms.replace(/(\s*\n\s*){6,}/g, '\n')
this replaces 6 line breaks into 1, but this effectively makes original 5 line breaks have more gap than 6 line breaks.
Is it possible to reference the occurrence in the replace string, so I can use something like:
generalsymptoms.replace(/(\s*\n\s*){6,}/g, '\n'.repeat(number_of_occurence/2))
Upvotes: 0
Views: 46
Reputation: 26558
' a a abaaaa'.replace(/(\s*a\s*){2,}/g, (matched, index, origin)=> {console.log(matched.replace(/\s/g, '')); return 'c'})
aaa
aaaa
which applied to here
generalsymptoms.replace(/(\n\s*\n){2,}/g, matched => '\n'.repeat(matched.replace(/ /g, '').length/2)))
Courtesy of my ex-colleague that hinted I can use a function in the replace method.
Upvotes: 1