removeLastExclamation.js (8kyu 58)

Codewars 알고리즘 풀이


Problem

  • Remove a exclamation mark from the end of string.
    • 문자열의 끝에 있는 느낌표(!)를 제거한다.


Solution 01

function removeLastExclamation(str) {
  let result = '';
  
  if (str[str.length - 1] === '!') {
    for (let i = 0; i < str.length - 1; i++) {
      result += str[i];
    }
    return result;
  } else {
    return str;
  }
}

removeLastExclamation('abc!');  // abc
removeLastExclamation('!abc');  // !abc
removeLastExclamation('!!!!');  // !!!


Solution 02

function removeLastExclamation(str) {
  if (str[str.length - 1] === '!') {
    return str.slice(0, -1);
  } else {
    return str;
  }
}

removeLastExclamation('abc!');  // abc
removeLastExclamation('!abc');  // !abc
removeLastExclamation('!!!!');  // !!!

slice() 메소드

선택한 element를 새 배열로 반환한다.


Solution 03

function removeLastExclamation(str) {
  return str[str.length - 1] === '!' ? str.slice(0, -1) : str;
}

removeLastExclamation('abc!');  // abc
removeLastExclamation('!abc');  // !abc
removeLastExclamation('!!!!');  // !!!


Solution 04

function removeLastExclamation(str) {
  return str.replace(/!$/g, '');
}

removeLastExclamation('abc!');  // abc
removeLastExclamation('!abc');  // !abc
removeLastExclamation('!!!!');  // !!!

정규표현식 (RegExp)

replace(): 대응되는 문자열을 찾아 다른 문자열로 치환한다.

$: 입력의 끝 부분에 대응


Solution 05

function removeLastExclamation(str) {
  let arr = str.split('');
  
  if (arr[arr.length - 1] === '!') {
    arr.pop();
  } else {
    arr;
  }
  return arr.join('');
}

removeLastExclamation('abc!');  // abc
removeLastExclamation('!abc');  // !abc
removeLastExclamation('!!!!');  // !!!

split() 메소드

문자열을 부분 문자열로 분할하고, 새 배열로 반환한다.

pop() 메소드

배열의 마지막 element를 제거하고, 그 element를 반환한다.

join() 메소드

배열의 모든 element를 결합하고, 새 문자열로 반환한다.