본문 바로가기
IT 인터넷/일반

문자열 > 링크 만들기 (Javascript)

by Banjubu 2025. 11. 23.
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