Problem
- Move the first letter of each word to the end of it, then add ‘ay’ to the end of the word.
- 각 단어의 첫 글자를 그 단어의 끝으로 이동시킨 다음, 단어의 끝에 ‘ay’를 추가한다.
- Leave punctuation marks untouched.
Solution 01
function pigIt(str) {
let arr = str.split(' ');
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].substring(1) + arr[i].substring(0, 1) + 'ay';
}
return arr.join(' ');
}
pigIt('Hello world'); // elloHay orldway
pigIt('Wassup bro'); // assupWay robay
Solution 02
function pigIt(str) {
return str.split(' ').map(i => i.substring(1) + i[0] + 'ay').join(' ');
}
pigIt('Hello world'); // elloHay orldway
pigIt('Wassup bro'); // assupWay robay
Solution 03
function pigIt(str) {
let arr = str.split(' ');
return arr.map(i => i.slice(1) + i.charAt(0) + 'ay').join(' ');
}
pigIt('Hello world'); // elloHay orldway
pigIt('Wassup bro'); // assupWay robay
Solution 04
function pigIt(str) {
return str.replace(/\b(\w)(\w*)\b/g, '$2$1ay');
}
pigIt('Hello world'); // elloHay orldway
pigIt('Wassup bro'); // assupWay robay
Solution 05
function pigIt(str) {
return str.replace(/(\w)(\w*)(\s|$)/g, '$2$1ay$3');
}
pigIt('Hello world'); // elloHay orldway
pigIt('Wassup bro'); // assupWay robay