2017-04-06 18 views
-2

我想向我的div中的网站链接添加锚定标记。 例如波纹管的文字在我的div使用javascript动态地将网站链接转换为字符串中的锚定标记

<div>I am Harsha Vardhan working for SSoft Pvt Ltd and its website is ssoft.com . My personal website is hv.com .</div> 

在上面的文字我想告诉ssoft.comhv.com其中假设在新标签页中打开的同时单击锚标记。我的文字可能包含任何数量的网站链接。

回答

0

这为我工作。从how to find and replace text url with links in jquery

function urlify(text) { 
 
     var urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/; 
 
     return text.replace(urlRegex, function(url) { 
 
      return '<a target="_blank" href="' + url + '">' + url + '</a>'; 
 
     }) 
 
    } 
 

 
\t var array = $("#originalText").text().split(' '), array1=""; 
 
    for(var i=0; i<array.length; i++) { 
 
    \t array1+=urlify(array[i])+" "; 
 
    \t 
 
    } 
 
    $("#modifiedText").html(array1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="originalText">I am Harsha Vardhan working for SSoft Pvt Ltd and its website is www.ssoft.com . My personal website is www.hv.co .</div> 
 

 
<div id="modifiedText"></div>

1

使用正则表达式,您可以从字符串中找到目标链接。 javascript .replace()找到每个链接并将其替换为锚标记。

$("div").html(function(i, html){ 
 
    return html.replace(/(\w+\.\w+)/g, "<a href='$1' target='_blank'>$1</a>"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div>I am Harsha Vardhan working for SSoft Pvt Ltd and its website is ssoft.com . My personal website is hv.com .</div>

相关问题