logo hsb.horse
← 블로그 목록으로 돌아가기

블로그

Twitter 동영상 URL에서 크기 정보를 추출하는 TypeScript 구현

Twitter(X) 동영상 URL에 포함된 해상도 정보를 정규표현식으로 추출하는 TypeScript 구현. URL 패턴과 크기 추출 방법을 정리했다.

게시일:

Twitter(X) 동영상 URL에는 해상도 정보가 들어 있다.

이 정보를 정규표현식으로 추출하는 구현을 정리한다.

구현

interface MediaSize {
height: number;
width: number;
}
function extractVideoSize(url: string): MediaSize | undefined {
const sizeRegex = /\/(\d+)x(\d+)\//;
const match = url.match(sizeRegex);
if (match && match[1] && match[2]) {
const width = parseInt(match[1], 10);
const height = parseInt(match[2], 10);
return { width, height };
}
return undefined;
}

포인트

정규표현식 /\/(\d+)x(\d+)\// 로 URL에서 1080x1920 같은 부분을 추출한다.

매치되면 parseInt 로 숫자로 변환해 반환하고, 매치되지 않으면 undefined 를 반환한다.

실행 예시

const inputs = [
"https://video.twimg.com/ext_tw_video/1111/pu/vid/avc1/1080x1920/1.mp4",
"https://video.twimg.com/ext_tw_video/1111/pu/pl/1.m3u8"
];
console.log(extractVideoSize(inputs[0]));
// { width: 1080, height: 1920 }
console.log(extractVideoSize(inputs[1]));
// undefined

mp4 URL에는 해상도 정보가 들어 있지만, m3u8 플레이리스트 URL에는 포함되지 않기 때문에 undefined 가 반환된다.

정리

Twitter 동영상 URL에서 해상도를 추출하는 구현은 정규표현식만으로도 간단히 만들 수 있다.

동영상 프리뷰나 썸네일 생성 전에 크기 정보를 먼저 읽고 싶을 때 쓸 수 있다.