var string = 'Hey @user123, can you upload a file';
function urlify(texts) {
var urlRegex = /(@[\w]+)/g;
return string.replace(urlRegex, function(match){
var name = match.slice(1);
return '<a href="https://stackoverflow.com/users/profiles/' + name + '">' + match + '</a>'
})
}
console.log(urlify(string));
返回Hey <a href="https://stackoverflow.com/users/profiles/user123">@user123</a>, can you upload a file
编辑多个:
使用字符串嘿@ user123,你可以上传文件,否则@admin可你看看
产量:
Hey <a href="https://stackoverflow.com/users/profiles/user123">@user123</a>, can you upload a file, otherwise <a href="https://stackoverflow.com/users/profiles/admin">@admin</a> can you take a look
...所以没有必要的循环。
编辑2:
function urlify(texts) {
var urlRegex = /(@[\w]+)/g;
return texts.replace(urlRegex, function(match){
var name = match.slice(1);
return '<a href="https://stackoverflow.com/users/profiles/' + name + '">' + match + '</a>'
})
}
$(document).ready(function(){
var text = $('.comment').html(function(index, text) {
return urlify(text)
});
});
http://plnkr.co/edit/tehEF4ESYXf4TTRR5lz8?p=preview
哪里有意见吗?很难说什么来循环,因为你没有显示任何HTML例子。 –
['$('.comment').each(function)'](http://api.jquery.com/each/)??没有关于您正在使用的DOM结构的一些想法,很难说任何有用的东西。 –
评论与类“content1”一起保存。 Phix提出了一个工作解决方案,但感谢提示.each(函数)将在下次尝试。 – Marla