Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
-
DDbecomes2D(2 D's) -
AAbecomes2A(2 A's) -
VremainsV(single character) -
IremainsI(single character) -
DremainsD(single character) -
MMMbecomes3M(3 M's) -
IremainsI(single character) -
LLbecomes2L(2 L's) -
EremainsE(single character) -
RRRRRbecomes5R(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.
