(Javascript) Convert plain text links to clickable links

后端 未结 4 1157
离开以前
离开以前 2021-01-06 06:03

Long story short, I have a website made under Wix.com editor, and coding was made possible a few months ago. I have set up a custom comment box, so users can post their comm

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 06:58

    I correct errors philipeachille's code because youtubeID parameter is not correct. I also correct direct youtube links.

    convertLinks = input => {
        let text = input;
        const aLink = [];
        const linksFound = text.match(/(?:www|https?)[^\s]+/g);
    
        if (linksFound != null) {
            for (let i = 0; i < linksFound.length; i++) {
                let replace = linksFound[i];
    
                if (!(linksFound[i].match(/(http(s?)):\/\//))) {
                    replace = 'http://' + linksFound[i]
                }
    
                let linkText = replace.split('/')[2];
    
                if (linkText.substring(0, 3) == 'www') {
                    linkText = linkText.replace('www.', '')
                }
    
                if (linkText.match(/youtu/)) {
                    const youtubeID = replace.split('/').slice(-1)[0].split('=')[1];
    
                    if (youtubeID === undefined || youtubeID === '') {
                        aLink.push('' + linkText + '');
                    } else {
                        aLink.push('');
                    }
                } else {
                    aLink.push('' + linkText + '');
                }
    
                text = text.split(linksFound[i]).map(item => {
                    return aLink[i].includes('iframe') ? item.trim() : item
                }).join(aLink[i]);
            }
            return text;
        }
        else {
            return input;
        }
    };
    

    Usage:

    const text = 'Hello. This is a link https://www.google.com and this is youtube video https://www.youtube.com/watch?v=O-hnSlicxV4';
    
    convertLinks(text);
    

提交回复
热议问题