使用 javascript 将网站链接动态转换为字符串中的锚标记
Convert website links dynamically to anchor tags in string using javascript
我想为我 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
,这些标签应该在单击时在新选项卡中打开。我的文字可能包含任意数量的网站链接。
使用正则表达式,您可以从字符串中找到目标 link。 javascript .replace()
找到每个 link 并将其替换为锚标记。
$("div").html(function(i, html){
return html.replace(/(\w+\.\w+)/g, "<a href='' target='_blank'></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>
这对我有用。参考自
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>
我想为我 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
,这些标签应该在单击时在新选项卡中打开。我的文字可能包含任意数量的网站链接。
使用正则表达式,您可以从字符串中找到目标 link。 javascript .replace()
找到每个 link 并将其替换为锚标记。
$("div").html(function(i, html){
return html.replace(/(\w+\.\w+)/g, "<a href='' target='_blank'></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>
这对我有用。参考自
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>