0

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

0

1 Answer 1

3

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 times

Then 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 )
Sign up to request clarification or add additional context in comments.

2 Comments

Since you're using the i flag anyway, it's safe to go with just [a-z] instead of [a-zA-Z].
@Nicholas Carey: It's awesome! I was so lost about how to find the number of matched letters, and your code not only solved it but also taught me how to express the replacement string with a function!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.