我想将锚标签添加到我的div中的网站链接。 例如,下面的文字在我的div中
<div>I am Harsha Vardhan working for SSoft Pvt Ltd and its website is ssoft.com . My personal website is hv.com .</div>
在上面的文字中,我想在锚标记中显示ssoft.com
和hv.com
,这些标记假设在点击时在新标签页中打开。我的文字可能包含任意数量的网站链接。
答案 0 :(得分:1)
使用正则表达式,您可以从字符串中找到目标链接。 javascript .replace()
找到每个链接并将其替换为锚标记。
$("div").html(function(i, html){
return html.replace(/(\w+\.\w+)/g, "<a href='$1' target='_blank'>$1</a>");
});
&#13;
<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>
&#13;
答案 1 :(得分: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>';
})
}
var array = $("#originalText").text().split(' '), array1="";
for(var i=0; i<array.length; i++) {
array1+=urlify(array[i])+" ";
}
$("#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>