Skip to content

Files

Latest commit

 

History

History
38 lines (27 loc) · 930 Bytes

split-strings.md

File metadata and controls

38 lines (27 loc) · 930 Bytes

Split Strings 6 Kyu

LINK TO THE KATA - REGULAR EXPRESSIONS STRINGS ALGORITHMS

Description

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

Examples:

* 'abc' =>  ['ab', 'c_']
* 'abcdef' => ['ab', 'cd', 'ef']

Solution

const solution = str => {
  if (str === '') return []

  let string = str
  const stringLength = str.length
  const result = []

  if (stringLength % 2 !== 0) string = `${str}_`

  for (let i = 0; i < Math.ceil(stringLength / 2); i++) {
    result.push(`${string[i * 2]}${string[i * 2 + 1]}`)
  }

  return result
}