(Javascript) Convert plain text links to clickable links

后端 未结 4 1160
离开以前
离开以前 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: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
    ' ) } else if ( linkText.match( /vimeo/ ) ) { let vimeoID = replace.split( '/' ).slice(-1)[0]; 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; } }

    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 stackoverflow.com is very clumsy and this developer.mozilla.org is not much better. This one apple.com 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

提交回复
热议问题