Code Wars: Word a10n (abbreviation)

Link to code challenge

The word i18n is a common abbreviation of internationalization in the developer community, used instead of typing the whole word and trying to spell it correctly. Similarly, a11y is an abbreviation of accessibility.

Write a function that takes a string and turns any and all "words" (see below) within that string of length 4 or greater into an abbreviation, following these rules:

A "word" is a sequence of alphabetical characters. By this definition, any other character like a space or hyphen (eg. "elephant-ride") will split up a series of letters into two words (eg. "elephant" and "ride").

The abbreviated version of the word should have the first letter, then the number of removed characters, then the last letter (eg. "elephant ride" => "e6t r2e").

function abbreviate(string) { // + sign in regex not needed let arr = string.split(/([-,\s]+)/g); /* parentheses split string at these characters but also stores them in array since we need these characters (like commas, dashes and spaces) when we join them back into a string. */ for (let i = 0; i < arr.length; i++) { if (arr[i].length <= 3) { arr[i] = arr[i]; } else { arr[i] = arr[i][0] + (arr[i].length - 2) + arr[i][arr[i].length - 1]; } } return arr.join(""); /* can just join array without parameters since commas, dashes, and spaces are already part of the array. */ }

Comments

Popular posts from this blog

Code Wars: Data Reverse (6 kyu)

Code Wars: longest_palindrome (6 kyu)

Code Wars: Find the odd int