Given a string and the task is to format the string into the License key.
- The input string contains alphanumeric characters and dashes
- The input string is separated by N+1 groups using N dashes.
- The output string must be grouped by K characters using a dash.
- The first group can be less than K characters but not Zero.
- The output string must not contain any lowercase character.
You have given the input string str and number K
Input: str = "dsf354g4dsg1" k = 4 Output: "DSF3-54G4-DSG1" Input: str = "d-sf354g4ds-g1dsfgdf-sfd5ds65-46" k = 6 Output: "D-SF354G-40DSGS-FGFSFD-DS6546" Input: str = " d-sf354';.;.';.'...,k/]gcs-hsfgdf-sfs6-46" Output: k = 5 Output: "DS-F354K-GCSHS-FGDFS-FS646"
To solve this problem we use the following steps:
- Create a function that takes two arguments str and k.
- Remove leading and ending white spaces using String.trim() method.
- Replace all the special characters using the String.replace() method and by searching with regex /[^a-zA-Z0-9]/g.
- Transform the string characters into uppercase by using String.toUpperCase() method.
- Convert the string into Array using the String.split() method. Now you have str is an array in which all the elements are uppercase characters and numbers (in the string form).
- Use a for loop and initialize the loop with the length of str and run it until the i is greater than 0 and after every iteration, the value of i decreases by k. Basically, we want a loop that runs from the backside of the str.
- Now concatenate the string at every iteration with a dash “-“
- Now on the str using Array.join() method convert the str into String and return the string from the function.
"DSF3-54G4-DSG1" "D-SF354G-40DSGS-FGFSFD-DS6546" "DS-F354K-GCSHS-FGDFS-FS646"
My Personal Notes arrow_drop_up
Please Login to comment...