JavaScript에서는 두 개의 문자열을 인자로 받아, 첫 번째 문자열(str1)이 두 번째 문자열(str2)로 시작하거나 끝나는지 판별하는 함수를 작성할 수 있습니다. 조건에 해당하면 true를, 그렇지 않으면 false를 반환하도록 구현합니다.
구현 로직
핵심 아이디어는 다음과 같습니다.
- str2가 str1보다 길다면 시작 또는 끝 부분과 일치할 수 없으므로 즉시 false를 반환합니다.
- 두 문자열이 완전히 같다면 true를 반환합니다.
- 그 외의 경우 str1의 앞부분(l2 길이만큼)과 뒷부분(l2 길이만큼)을 각각 잘라내어 str2와 비교합니다.
예제 코드
const str = 'this is an example string';
const startsOrEndsWith = (str1 = '', str2 = '') => {
// 검사 대상이 더 길면 일치 불가능
if(str2.length > str1.length){
return false;
};
// 두 문자열이 완전히 같은 경우
if(str1 === str2){
return true;
};
const { length: l1 } = str1;
const { length: l2 } = str2;
// 앞부분과 뒷부분 추출 후 비교
const startPart = str1.substring(0, l2);
const endPart = str1.substring(l1 - l2, l1);
return startPart === str2 || endPart === str2;
};
console.log(startsOrEndsWith(str, 'hel'));
console.log(startsOrEndsWith(str, 'ing'));
console.log(startsOrEndsWith(str, 'thi'));실행 결과
콘솔 출력 결과는 다음과 같습니다.
false true true
참고: 내장 메서드 활용
모던 JavaScript(ES6 이상)에서는 위 로직을 직접 구현하지 않고 startsWith()와 endsWith() 메서드를 사용해 더 간결하게 처리할 수 있습니다.
const checkString = (str1 = '', str2 = '') => {
return str1.startsWith(str2) || str1.endsWith(str2);
};
console.log(checkString('this is an example string', 'thi')); // true
console.log(checkString('this is an example string', 'xyz')); // false직접 구현하는 방식은 문자열 비교의 동작 원리를 이해하는 데 도움이 되며, 내장 메서드 방식은 실무에서 가독성과 유지보수성 측면에서 권장됩니다. 상황에 맞게 선택하여 사용하시기 바랍니다.