【问题标题】:Convert plain text links to clickable links将纯文本链接转换为可点击链接
【发布时间】:2018-04-03 16:23:47
【问题描述】:

长话短说,我在 Wix.com 编辑器下创建了一个网站,几个月前就可以进行编码了。 我已经设置了一个自定义评论框,所以用户可以发布他们的 cmets,并阅读其他人的。

现在的问题是,“评论输入”采用纯文本,每当发布链接时,它都会显示为纯文本,没有颜色,没有可点击性。

我想要一个“读取”cmets 列表的代码,并转换以“https”或“http”或“www”开头的每个文本...橙色且可点击(在新标签中打开)

请问有什么解决办法吗?

谢谢!

我尝试了很多方法,例如:

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

text95 = 显示的 cmets(它是一个文本,它会在尽可能多的 cmets 中重复出现)

【问题讨论】:

  • 当你说它是“一个在尽可能多的 cmets 中重复的文本”时,它是 &lt;ul&gt; 还是什么?这是一个 ID,因此在任何给定页面中不应有多个 ID。
  • 它在“中继器”内(我使用的是 Wix)

标签: javascript hyperlink


【解决方案1】:

看起来你的替换语法是错误的。

试试这样吧,我很确定这会奏效。

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;
}

调用它:

$w('#text95').innerHTML = linkify($w('#text95').html);

【讨论】:

  • 好答案..你确定给$w('#text95').html赋值会改变实际的html吗?
  • 是的,你是对的。应该是 .innerHTML 而不仅仅是 HTML。 已编辑
  • 大声笑你是什么意思我是对的?我问的是一个合理的问题,不是修辞。
  • 如果 $w('#text95') 返回一个 dom 元素,那么是的,它会是 innerHTML 但你知道 $w() 返回什么吗?
  • 无论如何.. 仍然对这个 $w 功能持怀疑态度,但 +1 为酷的 linkify 功能..
【解决方案2】:

这是我的答案(改进版,包括视频链接)。

另见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;
  }
}

这会将纯文本中的长而笨拙的链接替换为该文本中的短可点击链接。 (并且还将视频包装在响应式 iframe 中)

例子:

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

变成:

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

显示为:

这个笨拙的链接stackoverflow.com 非常笨拙,这个developer.mozilla.org 也好不了多少。这个apple.com不错,但是www可以去掉

【讨论】:

  • 太棒了!您是否还可以为 facebook、twitter、instagram 和linked in 等社交链接添加 if 语句?这样,如果它在文本中找到一个 facebook 链接,它会将其转换为一个 facebook url 图标?所以它会像这样
【解决方案3】:

我不确定$w 是什么,或者您是否真的可以这样分配html,但我猜这是jquery,因为$ 通常指的是jquery 对象。

你的尝试很接近,它会是..

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

试试吧..

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

【讨论】:

【解决方案4】:

我更正了 philipeachille 的代码错误,因为 youtubeID 参数不正确。我还更正了直接 youtube 链接。

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;
    }
};

用法:

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);

【讨论】:

  • 这里没有人认为链接在句尾,这意味着会有一个句号。因此,所有这些解决方案都将句点作为链接的一部分包含在内,不应该包含在内。
【解决方案5】:

如果字符串在任何地方都包含 URL,则将该字符串转换为链接。 我尝试上面的代码,但这对我来说不能正常工作。添加一些条件后,它起作用了。 谢谢你帮助我@user9590073

function convertLink(inputText) {
        var replacedText, replacePattern1, replacePattern2, replacePattern3;
    
    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&#\/%?=~_|!:,.;]*[-A-Z0-9+&#\/%=~_|])/gim;
    if (replacePattern1.test(inputText))
        inputText = inputText.replace(replacePattern1, '<a href="$1" target="_blank" style="color:blue">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    if (replacePattern2.test(inputText))
        inputText = inputText.replace(replacePattern2, '$1<a href="http://$2" target="_blank" style="color:blue">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])+[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    if (replacePattern3.test(inputText))
        replacedText = inputText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return inputText;
}

然后我将我的文本传递给 ConverLink Func 以打开带有可点击 URL 的模式。

$modalBody.find('div.news-content').html('<p>' + convertLink(response.NewsContent) + '</p>');

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2020-08-25
    • 2014-04-07
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多