상현에 하루하루
개발자의 하루

단어 요약하기

( 업데이트: )

internationaliaztion이란 단어는 개발자 커뮤니티에서 일반적으로 i18n이라는 약어로 사용된다. 전체 단어를 입력하고 철자를 정확하게 입력하는 대신 편리하게 사용하기위해서 약어로 사용한다. 마찬가지로 a11y또한 accessibility의 약어이다.

다음 규칙에 따라 문자열을 길이가 4 이상인 문자열 내의 모든 “단어”를 약어로 만드는 함수를 작성하십시오.

  • “단어”는 일련의 알파벳 문자입니다. 이 정의에 따라 공백이나 하이픈 같은 다른 문자는 일변의 문자를 두 단어로 분리합니다. (“elephant-red” -> “elephant” + “-” + “ride”)
  • 축약 된 단어 버전에는 첫 글자, 제거 된 글자 수, 마지막 글자가 있어야 합니다.

예시

abbreviate("elephant-rides are really fun!")
//          ^^^^^^^^*^^^^^*^^^*^^^^^^*^^^*
// words (^):   "elephant" "rides" "are" "really" "fun"
//                123456     123     1     1234     1
// ignore short words:               X              X

// abbreviate:    "e6t"     "r3s"  "are"  "r4y"   "fun"
// all non-word characters (*) remain in place
//                     "-"      " "    " "     " "     "!"
=== "e6t-r3s are r4y fun!"Code language: JavaScript (javascript)


function abbreviate(string) {
  const splitRegAfter = new RegExp('(-|,|!)', 'g');
  const splitRegBefore = new RegExp('(-)', 'g');
  const testReg = new RegExp('([a-zA-Z]){4,}', 'g');
  const stringArray = string.replace(splitRegAfter, ' $1 ').replace('  ', ' ').split(' ');
  for (const i in stringArray) {
    if (testReg.test(stringArray[i])) {
      console.log(stringArray[i], testReg.test(stringArray[i]));
      stringArray[i] = `${stringArray[i].substring(0,1)}${stringArray[i].length - 2}${stringArray[i].substring(stringArray[i].length - 1)}`
      console.log(stringArray[i])
    }
  }
  // 이렇게하면 실패함... 이유를 모르겠다. 
  // for (const i in stringArray) {
  //   if (testReg.test(stringArray[i])) {
  //     stringArray[i] = `${stringArray[i].substring(0,1)}${stringArray[i].length - 2}${stringArray[i].substring(stringArray[i].length - 1)}`
  //   }
  // }
  const result = stringArray.reduce((acc, cur) => {
    if (splitRegBefore.test(cur)) {
      return acc + cur;
    } else if (splitRegAfter.test(cur)) {
      return acc + cur;
    }
    return acc + ' '  + cur;
  }).replace(new RegExp('  ', 'g'),' ').replace(new RegExp('- ', 'g'), '-');
  return result;
}
Code language: JavaScript (javascript)

이렇게 길게 작성하였다. 나는 replace가 바꾸는 인자 부분도 함수로 정의 되있는지 몰랐다. MDN에서도 안나와서 그런 줄알았는데 인자부분에서도 바꿀수 있어서 이런 방식으로 짧게 구성할 수도있다는 것을 알게 되었다.

var find = /[a-z]{4,}/gi;
function replace(match) { return match[0] + (match.length - 2) + match[match.length - 1]; }

function abbreviate(string) {
  return string.replace(find, replace);
}Code language: JavaScript (javascript)

정규식 부분에서는 비슷하게 유추하였지만 유추한 내용으로 인자를 바꾸는 부분의 함수를 구현하기위해서 여러가지의 완벽하지 않은 방식으로 구성한 것을 회고하고 학습!