(Javascript) Convert plain text links to clickable links

后端 未结 4 1158
离开以前
离开以前 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:46

    I'm not sure what $w is or if you can really assign the html like that, but i'm guessing this is jquery since the $ most commonly refers to the jquery object.

    Your try was close, it would be..

    $('#text95').html($('#text95').html().replace(/((http:|https:)[^\s]+[\w])/g, '<a href="$1" target="_blank">$1</a>'));

    try it..

    $('#text95').html($('#text95').html().replace(/((http:|https:)[^\s]+[\w])/g, '<a href="$1" target="_blank">$1</a>'));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id=text95>
    stuff and stuff and http://ww.stuff.com stuff
    </div>

    0 讨论(0)
  • 2021-01-06 06:56

    Here is my answer (improved Version including video links).

    See also this Codepen here.

    const convertLinks = ( input ) => {
    
      let text = input;
      const linksFound = text.match( /(?:www|https?)[^\s]+/g );
      const aLink = [];
    
      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/ ) ) {
    
            let youtubeID = replace.split( '/' ).slice(-1)[0];
            aLink.push( '<div class="video-wrapper"><iframe src="https://www.youtube.com/embed/' + youtubeID + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>' )
          }
          else if ( linkText.match( /vimeo/ ) ) {
            let vimeoID = replace.split( '/' ).slice(-1)[0];
            aLink.push( '<div class="video-wrapper"><iframe src="https://player.vimeo.com/video/' + vimeoID + '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>' )
          }
          else {
            aLink.push( '<a href="' + replace + '" target="_blank">' + linkText + '</a>' );
          }
          text = text.split( linksFound[i] ).map(item => { return aLink[i].includes('iframe') ? item.trim() : item } ).join( aLink[i] );
        }
        return text;
    
      }
      else {
        return input;
      }
    }

    this replaces long and clumsy links within plain texts to short clickable links within that text. (And also wraps videos in responsive iframes)

    Example:

    This clumsy link https://stackoverflow.com/questions/49634850/javascript-convert-plain-text-links-to-clickable-links/52544985#52544985 is very clumsy and this http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split is not much better. This one www.apple.com is nice but www could be omitted

    Becomes:

    This clumsy link <a href="https://stackoverflow.com/questions/49634850/javascript-convert-plain-text-links-to-clickable-links/52544985#52544985" target="_blank">stackoverflow.com</a> is very clumsy and this <a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" target="_blank">developer.mozilla.org</a> is not much better. This one <a href="http://www.apple.com" target="_blank">apple.com</a> is nice but www could be omitted

    Is displayed as:

    This clumsy link stackoverflow.com is very clumsy and this developer.mozilla.org is not much better. This one apple.com is nice but www can be removed

    0 讨论(0)
  • 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('<a href="' + replace + '" target="_blank">' + linkText + '</a>');
                    } else {
                        aLink.push('<span class="video-wrapper"><iframe src="https://www.youtube.com/embed/' + youtubeID + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></span>');
                    }
                } else {
                    aLink.push('<a href="' + replace + '" target="_blank">' + linkText + '</a>');
                }
    
                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);
    
    0 讨论(0)
  • 2021-01-06 07:10

    It looks like you're replace syntax is wrong.

    Try something like this, I'm pretty sure this will work.

    function linkify(inputText) {
        var replacedText, replacePattern1, replacePattern2, replacePattern3;
    
        //URLs starting with http://, https://, or ftp://
        replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
    
        //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
        replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
        replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
    
        //Change email addresses to mailto:: links.
        replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
        replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
    
        return replacedText;
    }
    

    Calling it with:

    $w('#text95').innerHTML = linkify($w('#text95').html);
    
    0 讨论(0)
提交回复
热议问题