user7728939
user7728939

Reputation:

Javascript Regex: find & REPLACE letters that repeat LESS THAN a certain number of times

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

Upvotes: 0

Views: 96

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74277

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 )

Upvotes: 3

Related Questions