개요
이번 글의 핵심 아이디어는 두 개의 문자열을 입력받아, 한 문자열이 다른 문자열에 포함되어 있다면(즉, 둘이 부분 문자열 관계라면) true를 반환하고, 그렇지 않다면 false를 반환하는 함수를 만드는 것입니다.
예를 들어 다음과 같습니다.
isSubstr('hello', 'hello world') // true
isSubstr('can I use', 'I us') // true
isSubstr('can', 'no we are') // false
따라서 함수 내부에서는 먼저 어느 쪽이 더 긴 문자열인지(문자 수가 더 많은 쪽) 판별한 뒤, 나머지 짧은 문자열이 그 긴 문자열 안에 포함되어 있는지 검사하면 됩니다.
예제 코드
const str1 = 'This is a self-driving car.';
const str2 = '-driving c';
const str3 = '-dreving';
const isSubstr = (first, second) => {
if (first.length > second.length) {
return first.includes(second);
}
return second.includes(first);
};
console.log(isSubstr(str1, str2));
console.log(isSubstr(str1, str3));
출력 결과
콘솔에는 다음과 같은 결과가 출력됩니다.
true false
동작 원리
- 먼저 두 문자열의
length속성을 비교하여 어느 쪽이 더 긴지 판별합니다. String.prototype.includes()메서드는 인자로 전달된 문자열이 대상 문자열에 포함되어 있으면true, 그렇지 않으면false를 반환합니다.- 첫 번째 문자열이 더 길면
first.includes(second)로 검사하고, 그렇지 않으면second.includes(first)로 검사합니다. - 예제의
str3 = '-dreving'은 철자가 달라str1에 포함되어 있지 않으므로false가 출력됩니다.
이처럼 길이 비교와 includes() 메서드만 활용하면 별도의 복잡한 로직 없이도 두 문자열 간의 부분 문자열 관계를 간단하게 확인할 수 있습니다.