728x90
반응형
SMALL
const text = 'Check this(example.com) out. Also (test.com/foo). And [en.wikipedia.org/wiki/React_(software)]. Unbalanced test.com/bar)';
// Updated regex to support optional protocol
const urlPattern = /((?:https?:\/\/)?(?:[\w-]+\.)+[a-z]{2,}(?:\/[^\s]*)?)/gi;
const parts = text.split(urlPattern);
console.log('Parts:', parts);
parts.forEach(part => {
if (part.match(urlPattern)) {
let cleanUrl = part;
let suffix = '';
// 끝에서부터 특수문자 제거 (반복적으로 체크)
while (cleanUrl.length > 0) {
const lastChar = cleanUrl.slice(-1);
// 제거할 특수문자 목록
if (/^[)\]"'\u3002\uff0c\uff1b\uff1a\u201c\u201d\u2018\u2019\uff01\uff1f\u3001\u3002.,;:!?]$/.test(lastChar)) {
// 닫는 괄호인 경우 짝이 맞는지 확인
if (lastChar === ')') {
const openCount = (cleanUrl.match(/\(/g) || []).length;
const closeCount = (cleanUrl.match(/\)/g) || []).length;
// 짝이 맞으면 URL의 일부로 간주하고 제거 중단
if (openCount === closeCount) {
break;
}
}
// 특수문자 제거하고 suffix에 추가
cleanUrl = cleanUrl.slice(0, -1);
suffix = lastChar + suffix;
} else {
// 특수문자가 아니면 중단
break;
}
}
console.log('Original:', part);
console.log('Clean:', cleanUrl);
console.log('Suffix:', suffix);
// href check
let href = cleanUrl;
if (!href.startsWith('http://') && !href.startsWith('https://')) {
href = 'https://' + href;
}
console.log('Href:', href);
}
});
728x90
반응형
LIST
'IT 인터넷 > 일반' 카테고리의 다른 글
| 75세 노인, "쓰레기 치우는 주제에!" 쓰레기 불법 투기 제지한 환경미화원 폭행하고 무고... 집행유예 선고 (0) | 2025.06.17 |
|---|---|
| ✨2025년, 블로그에 AI 안 쓰면 손해?! (2) | 2025.05.28 |
| 영어 교육 사이트 추천합니다. (0) | 2025.04.30 |
| 🔥 MBTI 유형별 죽기 직전에 남기는 말들 ⏳ (0) | 2025.02.24 |
| 🇰🇷 한국인이 일상에서 가장 자주 사용하는 단어, 동사, 관용구 🇺🇸 (0) | 2025.02.23 |