Open In App

Compressing String in JavaScript

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Compressing a string involves replacing repeated characters with their count followed by the character itself. For example, string aaabbccc can be compressed to 3a2b3c.

Examples:

Input: string = aaabbbccc
Output: compressed string = 3a3b3c

Input:  string = heeeeelllllloooooo
Output:  compressed string = 1h5e6l60

Using JavaScript loops

We can solve this problem by iterating through the string and count consecutive characters using the JavaScript loop and append the corresponding count and the character to a new string.

Example: The below code will explain the use of JavaScript loops to compress a string.

JavaScript
function compressStringLoop(str) {
    let compressed = '';
    let count = 1;
    for (let i = 0; i < str.length; i++) {
        if (str[i] === str[i + 1]) {
            count++;
        } else {
            compressed += count + str[i];
            count = 1;
        }
    }
    console.log(compressed);
}
compressStringLoop("aaabbccc");
compressStringLoop("heeellllooooo");

Output
3a2b3c
1h3e4l5o

Using Regular Expressions

We can solve this problem by using a regular expression to match consecutive characters and replace them with their count followed by the character using the replace() method.

Example: The below code uses the regular expressions to compress the given string in JavaScript.

JavaScript
function compressStringRegex(str) {
    return str.replace(
        /(.)\1*/g,
        (match, char) =>
            match.length + char);
}
let compressedStrRegex1 =
    compressStringRegex("aaabbbcc");
let compressedStrRegex2 =
    compressStringRegex("heeellllooooo");
console.log(compressedStrRegex1);
console.log(compressedStrRegex2);

Output
3a3b2c
1h3e4l5o

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads