removeFirstAndLast.js (8kyu 15)

Codewars 알고리즘 풀이


Description

  • Your goal is to create a function that removes the first and last characters of a string.
    • 문자열의 첫 번째 글자와 마지막 글자를 제거한다.



Solution 01

function removeFirstAndLast(str) {
  let result = '';
  
  for (let i = 1; i < str.length - 1; i++) {
    result += str[i];
  }
  
  return result;
}

removeFirstAndLast('');          // ''
removeFirstAndLast('Hello');     // ell
removeFirstAndLast('World');     // orl
removeFirstAndLast('Codewars');  // odewar


Solution 02

function removeFirstAndLast(str) {
  let arr = str.split('');
  
  arr.shift();
  arr.pop();
  
  return arr.join('');
}

removeFirstAndLast('');          // ''
removeFirstAndLast('Hello');     // ell
removeFirstAndLast('World');     // orl
removeFirstAndLast('Codewars');  // odewar


Solution 03

function removeFirstAndLast(str) {
  return str.substring(1, str.length - 1);
}

removeFirstAndLast('');          // ''
removeFirstAndLast('Hello');     // ell
removeFirstAndLast('World');     // orl
removeFirstAndLast('Codewars');  // odewar


Solution 04

function removeFirstAndLast(str) {
  return str.slice(1, -1);
}

removeFirstAndLast('');          // ''
removeFirstAndLast('Hello');     // ell
removeFirstAndLast('World');     // orl
removeFirstAndLast('Codewars');  // odewar


Solution 05

function removeFirstAndLast(str) {
  return str.split('').splice(1, str.length - 2).join('');
}

removeFirstAndLast('');          // ''
removeFirstAndLast('Hello');     // ell
removeFirstAndLast('World');     // orl
removeFirstAndLast('Codewars');  // odewar


Solution 06

function removeFirstAndLast(str) {
  return str.replace(/^.|.$/g, '');
}

removeFirstAndLast('');          // ''
removeFirstAndLast('Hello');     // ell
removeFirstAndLast('World');     // orl
removeFirstAndLast('Codewars');  // odewar