How to decrease size of a string by using preceding numbers - JavaScript?

Let's say our original string is the following with repeated letters −

var values = "DDAAVIDMMMILLERRRRR";

We want to remove the repeated letters and precede letters with numbers. For this, use replace() along with regular expression.

Syntax

string.replace(/(.)\1+/g, match => match.length + match[0])

How It Works

The regular expression /(.)\1+/g matches any character followed by one or more repetitions of the same character. The replacement function returns the count plus the original character.

Example

Following is the code −

var values = "DDAAVIDMMMILLERRRRR";
var precedingNumbersInString = values.replace(/(.)\1+/g, obj => obj.length + obj[0]);
console.log("The original string value=" + values);
console.log("String value after preceding the numbers =");
console.log(precedingNumbersInString);

Output

This will produce the following output on console −

The original string value=DDAAVIDMMMILLERRRRR
String value after preceding the numbers =
2D2AVID3MI2LE5R

Breakdown of the Result

Let's understand how the compression works:

  • DD becomes 2D (2 D's)
  • AA becomes 2A (2 A's)
  • V remains V (single character)
  • I remains I (single character)
  • D remains D (single character)
  • MMM becomes 3M (3 M's)
  • I remains I (single character)
  • LL becomes 2L (2 L's)
  • E remains E (single character)
  • RRRRR becomes 5R (5 R's)

Additional Example

var test1 = "AABBCCCCDEEEEE";
var test2 = "HELLO";
var test3 = "AAAAAAA";

console.log(test1 + " -> " + test1.replace(/(.)\1+/g, obj => obj.length + obj[0]));
console.log(test2 + " -> " + test2.replace(/(.)\1+/g, obj => obj.length + obj[0]));
console.log(test3 + " -> " + test3.replace(/(.)\1+/g, obj => obj.length + obj[0]));
AABBCCCCDEEEEE -> 2A2B4CDE5E
HELLO -> HE2LO
AAAAAAA -> 7A

Conclusion

This string compression technique uses regular expressions to identify consecutive repeated characters and replaces them with their count followed by the character. It's effective for strings with many consecutive duplicates.

Updated on: 2026-03-15T23:19:00+05:30

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements