Formatting Software License Key in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string str, as the first argument and an Integer, n as the second argument. The string str is composed of alphanumeric characters and dashes.

The dashes split the alphanumeric characters within the string into groups. (i.e. if there are n dashes, the string is split into n+1 groups). The dashes in the given string are possibly misplaced.

We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character).

To satisfy this requirement, we will reinsert dashes. Moreover, our function needs to convert all the lowercase letters in the string to uppercase.

For example, if the input to the function is −

const str = '8-4B0t37-k';
const num = 4;

Then the output should be −

const output = '84B0-T37K';

Output Explanation:

The string str has been split into two parts, each part has 4 characters.

Example

The code for this will be −

 Live Demo

const str = '8-4B0t37-k';
const num = 4;
const formatKey = (str = '', num = 1) => {
   let acc = '';
   let flag = num;
   for(let i = str.length - 1; i >= 0; i--){
      const char = str.charAt(i);
      if(char !== '-') {
         if(flag === 0) {
            acc = `-${acc}`;
            flag = num;
         };
         acc = `${char.toUpperCase()}${acc}`;
         flag -= 1;
      };
   };
   return acc;
};
console.log(formatKey(str, num));

Code Explanation

The steps we took in our function formatKey() are −

  • We iterated in reverse, so that we can accomodate for the case of remaining chars < num (since the first part doesn't have the compulsion of having exactly num characters).

  • We kept a count of inserted characters. And when it was 0, we inserted dash and reset to num.

Output

And the output in the console will be −

84B0-T37K
raja
Published on 04-Mar-2021 06:02:50
Advertisements