在html链接标签中打开所有url,而不使用javascript转换任何其他链接



我有一个REST服务,它提供带文本和链接的字符串。字符串中可以是url,也可以是已经用HTML链接标签格式化的链接。

我正在寻找一种方法,在不改变任何现有链接标签的情况下,将所有URL转换为html链接。

我使用了这个函数,但它只完成了一半的工作,因为它将URL转到现有链接标签的href属性中

var text = "Test linktag: <a target='_blank' href='http://www.google.com'>Google</a>  some other text" + "<br>" +
            "Test url:  http://www.google.com some other text";
function urlify(text) {
    var exp = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig;
    var text1 = text.replace(exp, "<a href='$1'>$1</a>");
    var exp2 = /(^|[^/])(www.[S]+(b|$))/gim;
    return text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
}
var result = urlify(text)
// result will give:
// Test linktag: <a target='_blank' href='<a href='http://www.google.com'>http://www.google.com</a>'>Google</a>  some other text<br>Test url:  <a href='http://www.google.com'>http://www.google.com</a> some other text

您可以从这个链接获得帮助

<div tabIndex="0" title="People Picker" class="ms-inputuserfield">Administrator</div> 

动态添加锚点标签

我把自己标记为重复,因为这个问题(显然)已经被问过了,而且已经有了正确的答案。

这个答案不是一个解决方案,但它是面对我的问题的最佳方式:

如何用链接替换普通URL?

最新更新