코샵
끄적끄적 코딩 공방
코샵

인기 글

  • 분류 전체보기 (479) N
    • MongoDB (4)
    • 일기장 (4)
    • Unity (138)
      • Tip (41)
      • Project (1)
      • Design Pattern (8)
      • Firebase (6)
      • Asset (2)
    • 파이썬 (127)
      • Basic (40)
      • OpenCV (8)
      • Pandas (15)
      • PyQT (3)
      • SBC(Single Board Computer) (1)
      • 크롤링 (14)
      • Fast API (29)
      • Package (6)
    • Linux (4)
    • C# (97)
      • Algorithm (11)
      • Window (7)
    • TypeScript (48) N
      • CSS (10) N
    • Git (11)
    • SQL (5)
    • Flutter (10)
      • Tip (1)
    • System (1)
    • BaekJoon (6)
    • Portfolio (2)
    • MacOS (1)
    • 유틸리티 (1)
    • 서비스 (6)
    • 자동화 (3)
    • Hobby (10)
      • 물생활 (10)
      • 식집사 (0)
전체 방문자
오늘
어제

최근 댓글

최근 글

반응형
hELLO · Designed By 정상우.
코샵

끄적끄적 코딩 공방

TypeScript

[JavaScript] 문자열 검색과 비교

2025. 1. 25. 10:59
반응형

소개

JavaScript에서 문자열을 다루는 다양한 메서드들, 특히 문자열 검색과 비교에 사용되는 메서드들을 자세히 알아보고, 각 메서드의 사용법과 차이점을 살펴보겠습니다.

기본 문자열 검색 메서드

1. indexOf

문자열 내에서 특정 문자열의 첫 번째 등장 위치를 찾습니다.

const text = "Hello, World!";

console.log(text.indexOf("World"));     // 7
console.log(text.indexOf("world"));     // -1 (대소문자 구분)
console.log(text.indexOf("o"));         // 4
console.log(text.indexOf("o", 5));      // 7 (시작 위치 지정)

// 실전 활용
const hasWorld = text.indexOf("World") !== -1;  // true

2. includes

문자열이 포함되어 있는지 여부를 boolean으로 반환합니다.

const text = "Hello, World!";

console.log(text.includes("World"));     // true
console.log(text.includes("world"));     // false
console.log(text.includes("o", 5));      // true (시작 위치 지정)

// 실전 활용
const isValidEmail = email.includes("@");  // 간단한 이메일 체크

3. startsWith

문자열이 특정 문자열로 시작하는지 확인합니다.

const filename = "image.jpg";

console.log(filename.startsWith("image"));  // true
console.log(filename.startsWith("img"));    // false
console.log(filename.startsWith("age", 2)); // true (시작 위치 지정)

// 실전 활용
const isImageFile = filename.startsWith("image.");

4. endsWith

문자열이 특정 문자열로 끝나는지 확인합니다.

const filename = "document.pdf";

console.log(filename.endsWith(".pdf"));     // true
console.log(filename.endsWith("doc"));      // false
console.log(filename.endsWith("ment", 8));  // true (길이 제한)

// 실전 활용
const isPdfFile = filename.endsWith(".pdf");

 

5. lastIndexOf

문자열 내에서 특정 문자열의 마지막 등장 위치를 찾습니다.

const text = "Hello, Hello, World!";

console.log(text.lastIndexOf("Hello"));     // 7
console.log(text.lastIndexOf("o"));         // 13
console.log(text.lastIndexOf("o", 5));      // 4 (뒤에서부터 검색)

6. search

정규표현식을 사용한 검색이 가능합니다.

const text = "Hello, World! 123";

console.log(text.search(/\d+/));        // 13 (숫자 위치)
console.log(text.search(/[A-Z]/));      // 0 (대문자 위치)

// 실전 활용
const hasNumber = text.search(/\d/) !== -1;

7. match

정규표현식과 매칭되는 모든 결과를 배열로 반환합니다.

const text = "Hello 123 World 456";

console.log(text.match(/\d+/g));        // ["123", "456"]
console.log(text.match(/[A-Z]\w+/g));   // ["Hello", "World"]

// 실전 활용
const numbers = text.match(/\d+/g)?.map(Number) || [];

8. matchAll

정규표현식과 매칭되는 모든 결과를 반복자로 반환합니다.

const text = "cat, bat, sat, fat";
const regex = /[a-zA-Z]at/g;

for (const match of text.matchAll(regex)) {
    console.log(match[0]);  // "cat", "bat", "sat", "fat"
}

실전 활용 예제

1. 이메일 유효성 검사

function validateEmail(email) {
    return email.includes('@') && 
           email.includes('.') && 
           !email.startsWith('@') && 
           !email.endsWith('.');
}

// 더 정확한 검증
function validateEmailRegex(email) {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
}

2. 파일 확장자 확인

function getFileType(filename) {
    const imageExts = ['.jpg', '.png', '.gif'];
    const documentExts = ['.pdf', '.doc', '.txt'];

    if (imageExts.some(ext => filename.endsWith(ext))) {
        return 'image';
    }

    if (documentExts.some(ext => filename.endsWith(ext))) {
        return 'document';
    }

    return 'unknown';
}

3. URL 파싱

function parseUrl(url) {
    return {
        protocol: url.startsWith('https') ? 'https' : 'http',
        hasWww: url.includes('www'),
        domain: url.match(/^(?:https?:\/\/)?(?:www\.)?([^\/]+)/i)?.[1],
    };
}

성능 고려사항

메서드별 성능 비교

const text = "Hello, World!";
const searchTerm = "World";

// 1. indexOf (가장 빠름)
console.time('indexOf');
text.indexOf(searchTerm) !== -1;
console.timeEnd('indexOf');

// 2. includes
console.time('includes');
text.includes(searchTerm);
console.timeEnd('includes');

// 3. 정규표현식
console.time('regex');
new RegExp(searchTerm).test(text);
console.timeEnd('regex');
저작자표시 비영리 변경금지 (새창열림)

'TypeScript' 카테고리의 다른 글

[REST API] RESTful API 설계 가이드  (1) 2025.01.29
[HTTP Header 다루기] fetch API의 Headers 인터페이스  (0) 2025.01.26
[Next.js] HTTP 요청 구현하기 : fetch vs axios  (0) 2025.01.24
[Chrome Extension] Manifest V3 가이드  (2) 2025.01.21
next.config.js 커스터마이징  (0) 2025.01.08
    'TypeScript' 카테고리의 다른 글
    • [REST API] RESTful API 설계 가이드
    • [HTTP Header 다루기] fetch API의 Headers 인터페이스
    • [Next.js] HTTP 요청 구현하기 : fetch vs axios
    • [Chrome Extension] Manifest V3 가이드
    코샵
    코샵
    나의 코딩 일기장

    티스토리툴바