Open In App

JavaScript Program to Return Original String of Compressed String

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

The compressed string follows a format where each character is followed by its count. we need to print a string having the same number of characters present in the compressed string.

Below are the approaches to return original string of compressed string using

Example:

Input: compressedString= "a3b2c1"
Output: originalString="aaabbc"

These are the following approaches:

Using Regular Expressions

This approach uses regular expressions to identify patterns in the compressed string and replace them with their expanded forms. The regular expression /([a-zA-Z])(\d+)/g is used to match a letter followed by a number.

Example: This example uses Regular Expressions to get the original string of compressed string.

JavaScript
function decompressWithRegex(str) {
    return str.replace(/([a-zA-Z])(\d+)/g, (_, char, count) =
            char.repeat(Number(count)));
}

const compressedStr = "g0e2k3";
console.log(decompressWithRegex(compressedStr));

Output
eekkk

Using String Manipulation

In this approach, we look at each character in the compressed string one by one. If a character is a letter, it just adds that letter to the result string. If the character is a number, it repeats the previous letter in the result string by the value of that number. This process continues until the entire compressed string is processed, resulting in the original string.

Example: This example uses String Manipulation to return original string of compressed string.

JavaScript
function decompressWithStringManipulation(str) {
    let result = "";
    for (let i = 0; i < str.length; i++) {
        if (isNaN(str[i])) {
            result += str[i];
        } else {
            const count = parseInt(str[i]);
            result += result[result.length - 1].repeat(count - 1);
        }
    }
    return result;
}

const compressedStr = "g2f3s1";
console.log(decompressWithStringManipulation(compressedStr));

Output
ggfffs

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads