简体   繁体   中英

Javascript string replace regex proportion to occurence?

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))

' 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM