Computer >> Computer tutorials >  >> Programming >> Javascript

Function to decode a string in JavaScript


We are given an encoded string, and we are required to process it through a function that returns its decoded string.

The encoding rule is −

n[encodedString], where the encodedString inside the square brackets is being repeated exactly n times.

And n is guaranteed to be a positive integer.

We can assume that the input string is always valid; No extra white spaces, square brackets are well−formed, etc.

For example − If the input is −

const str = "3[a]2[bc]";

Then the output should be −

const output: "aaabcbc";

Example

The code for this will be −

const str = "3[a]2[bc]";
const helper = (str = '') => {
   return str.replace(/(\d+\[\w+\])/gi, item => {
      let match = /(\d+)\[(\w+)\]/.exec(item);
      let repeat = parseInt(match[1]);
      let pattern = match[2];
      let result = "";
      while(repeat−− > 0) {
         result += pattern;
      }
      return result;
   });
};
const decodeString = function(str) {
   while(/\d+\[\w+\]/gi.test(str)) {
      str = helper(str);
   }
   return str;
};
console.log(decodeString(str));

Output

And the output in the console will be −

aaabcbc