【问题标题】:Replace plain URL with link if domain matches如果域匹配,则将纯 URL 替换为链接
【发布时间】:2015-02-14 23:40:48
【问题描述】:

您好,我想像这样替换字符串:

"Hey this is a link to somesite.co bye bye";

"Hey this is a link to <a href="somesite.co">somesite.co</a> bye bye";

但前提是 somesite.co 被发现,而不是 someotherdunno.co 域

我尝试的是拆分所有字符串并检查每个单词,以便如果域在单词中,我用那个替换它

<a href="$domainFound">$domainFound</a> 

但我不喜欢这个解决方案,我确信有一些更快/更好的方法可以实现这一点,你有什么线索吗?

谢谢

【问题讨论】:

  • 创建一个仅匹配somesite.co 的正则表达式。然后使用字符串replace将字符串替换为href protion。

标签: javascript regex string replace hyperlink


【解决方案1】:

您可以使用正则表达式替换然后追加。

var str = "Hey this is a link to somesite.co bye bye";
str = str.replace(/(somesite\.co)/g, "<a href="$1">$1</a>");
var a = document.createElement('a');
a.outerHTML = str;
document.body.appendChild(a);

【讨论】:

  • @sbaaaang 等待 :) 很高兴有帮助 :)
【解决方案2】:

您可以尝试查找已知域,然后检查它是否是有效的 url。

var i, len, re, domain, secure,
  string = 'Your string that contains my-domain.com !'
  domains = [ 'com', 'co' ];

for ( i = 0, len = domains.length; i < len; i++ ) {
    re = new RegExp( '(?:\\s|^)(\\S*?\\.'+ domains[ i ] +')(?:\\s|$)', 'g' );

    // find all possible domains in the string
    while( domain = re.exec( string ) ) {
        domain = domain[ 1 ];
        if ( checkDomain( domain ) ) {
            string = string.replace( domain, '<a href="'+ domain +'">'+ domain +'</a>' );
        }
    }
}

console.log( string );  
//Your string that contains <a href="my-domain.com">my-domain.com</a> !

function checkDomain ( domain ) {
    // returns true if the domain exists
    return true;
}

Try it on jsFiddle

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 2012-01-14
    • 1970-01-01
    • 2021-04-15
    • 2013-11-02
    • 2011-05-26
    相关资源
    最近更新 更多