This question is a derivative from another one here:
Say, for the string "lllrrrrrrrruuddddr", how to replace those letters that repeat less than 4 times with "-", thus resulting in "---rrrrrrrr--dddd-".
This question is a derivative from another one here:
Say, for the string "lllrrrrrrrruuddddr", how to replace those letters that repeat less than 4 times with "-", thus resulting in "---rrrrrrrr--dddd-".
The easiest way is the simplest way.
[a-zA-Z] matches a single ASCII letter([a-zA-Z]) is a capturing group\1 is a backreference that tells us to match again exactly what was matched by capturing group #1 again\1* tells us to match that backreference zero or more timesThen you just need this:
function replaceRunsWithLengthLessThan( s, n, r ) {
const replaced = typeof(s) !== "string"
? s
: s.replace( rxSingleLetterRun, m => m.length < n ? r : m )
;
return replaced;
}
const rxSingleLetterRun = /([a-zA-Z])\1*/ig;
which can be invoked as
const orig = 'aaaa bbb cc d eeeeee'
const repl = replaceRunsWithLengthLessThan( orig, 4, '-');
and which produces the expected value: aaaa - - - eeeeee.
Edited to note: If you want to replace the short runs with as many dashes as the length of the run, you just need to change
s.replace( rxSingleLetterRun, m => m.length < n ? r : m )
with
s.replace( rxSingleLetterRun, m => m.length < n ? r.repeat(m.length) : m )
i flag anyway, it's safe to go with just [a-z] instead of [a-zA-Z].