Created
February 24, 2019 13:13
-
-
Save AndriiBozh/9637c916250f32a537cd947763e2e58c to your computer and use it in GitHub Desktop.
CodeWars: Split and Replace, if Needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ASSIGNMENT | |
____________________________ | |
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: | |
solution('abc') // should return ['ab', 'c_'] | |
solution('abcdef') // should return ['ab', 'cd', 'ef'] | |
____________________________ | |
SOLUTION | |
____________________________ | |
function solution(str){ | |
let re = /[a-z]{1,2}/g; | |
let splitted = str.match(re); | |
return splitted.map(function(item) { | |
return item.length > 1 ? item : item + '_'; | |
}); | |
}; | |
solution('abcdef') | |
___________________________ | |
it could be shortened: | |
function solution(str){ | |
let re = /[a-z]{1,2}/g; | |
return str.match(re).map(function(item) { | |
return item.length > 1 ? item : item + '_'; | |
}); | |
}; | |
solution('abcdef') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment