Skip to content

Instantly share code, notes, and snippets.

@AndriiBozh
Created February 24, 2019 13:13
Show Gist options
  • Save AndriiBozh/9637c916250f32a537cd947763e2e58c to your computer and use it in GitHub Desktop.
Save AndriiBozh/9637c916250f32a537cd947763e2e58c to your computer and use it in GitHub Desktop.
CodeWars: Split and Replace, if Needed
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