자바스크립트에서 문자열이 포함되었는지 알아내는 방법에는 다양한 방법이 있지만, 주요적인 방법은 다음과 같습니다.
1. String.prototype.includes() 메서드
String.prototype.includes() 메서드는 주어진 문자열이 현재 문자열에 포함되어 있는지 여부를 나타내는 불리언 값을 반환합니다. 이 메서드는 대/소문자를 구분하므로, 대/소문자를 구분하지 않고 포함 여부를 판단하려면 toLowerCase() 또는 toUpperCase() 메서드를 사용해야 합니다.
const str = 'hello world';
console.log(str.includes('hello')); // true
console.log(str.includes('World')); // false
console.log(str.toLowerCase().includes('world')); // true
2. String.prototype.indexOf() 메서드
String.prototype.indexOf() 메서드는 현재 문자열에서 주어진 문자열이 처음 등장하는 인덱스를 반환합니다. 만약 문자열이 포함되어 있지 않다면 -1을 반환합니다.
const str = 'hello world';
console.log(str.indexOf('hello')); // 0
console.log(str.indexOf('World')); // -1
3. 정규표현식
정규표현식을 사용하여 문자열이 포함되었는지 여부를 판단할 수 있습니다.
const str = 'hello world';
console.log(/hello/.test(str)); // true
console.log(/World/.test(str)); // false
4. String.prototype.startsWith()
String.prototype.startsWith() 메서드는 현재 문자열이 주어진 문자열로 시작하는지 여부를 나타내는 불리언 값을 반환합니다. 이 메서드도 대/소문자를 구분하므로, 대/소문자를 구분하지 않고 시작 여부를 판단하려면 toLowerCase() 또는 toUpperCase() 메서드를 사용해야 합니다.
const str = 'hello world';
console.log(str.startsWith('hello')); // true
console.log(str.startsWith('Hello')); // false
console.log(str.toLowerCase().startsWith('hello')); // true
5. String.prototype.endsWith()
String.prototype.endsWith() 메서드는 현재 문자열이 주어진 문자열로 끝나는지 여부를 나타내는 불리언 값을 반환합니다. 이 메서드도 대/소문자를 구분하므로, 대/소문자를 구분하지 않고 끝 여부를 판단하려면 toLowerCase() 또는 toUpperCase() 메서드를 사용해야 합니다.
const str = 'hello world';
console.log(str.endsWith('world')); // true
console.log(str.endsWith('World')); // false
console.log(str.toUpperCase().endsWith('WORLD')); // true
'자바스크립트' 카테고리의 다른 글
[자바스크립트] filter() 사용법 (0) | 2023.03.12 |
---|---|
[자바스크립트] 화살표 함수 기초 (0) | 2023.03.12 |
[자바스크립트] 디바운싱과 쓰로틀링 (0) | 2023.03.11 |
[자바스크립트] DocumentFragment 성능 개선 방법 (0) | 2023.03.11 |
[자바스크립트] 부모 노드, 자식 노드, 형제 노드 찾기 (0) | 2023.03.11 |
댓글