简体   繁体   English

将文本链接转换为超链接和锚文本

[英]Converting Text Link to Hyper Link and Anchor Text

I have a question about converting text links to hyper links. 我有一个关于将文本链接转换为超级链接的问题。 I did it successfully by using this code from this link; 我通过使用此链接中的代码成功完成了此操作; How to replace plain URLs with links? 如何用链接替换纯URL?

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

The output of this code is like; 该代码的输出类似于:

Input: http://www.tinymoviez.com Output: <a href='http://www.tinymoviez.com'>http://www.tinymoviez.com</a>

Now what i want is to get anchor text not in link form, it should be without 'http://www.' 现在,我要获取的锚文本不是链接形式,应该没有'http://www.'

In short i need the output as 总之我需要输出

<a href='http://www.tinymoviez.com'>tinymoviez.com</a>

But keep in mind that it should be auto, i will convert bulk of links at a time. 但是请记住,它应该是自动的,我会一次转换大量链接。

How can i do that??? 我怎样才能做到这一点??? Any help will be appreciated. 任何帮助将不胜感激。

This works!!! 这有效!!!

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(http|ftp|https):\/\/([\w-]+\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?)/ig;
    return text.replace(exp,"<a href='$1'>$3</a>"); 
}

Input text 输入文本

"http://stackoverflow.com/questions/579335/javascript-regexp-to-wrap-urls-and-emails-in-anchors";

Output: 输出:

<a href='http://stackoverflow.com/questions/579335/javascript-regexp-to-wrap-urls-and-emails-in-anchors'>stackoverflow.com</a>

Here is a working JsFiddle 这是一个工作的JsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM