我创建了一个解析文本的函数,我希望它返回一个完整的链接说:
@tw将返回<a href="http://www.twitter.com/tw"></a>
而是返回http://www.twitter.com/tw
而没有标记。如何附加标签以包含文本tw,并将标记返回到html?
String.prototype.parseUsername = function() {
return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
var username = u.replace("@","")
var twitter_link = document.createElement("a");
twitter_link.href = "http://www.twitter.com/"+username
twitter_link.target = "_blank"
console.log(twitter_link)
return twitter_link;
});
};
答案 0 :(得分:0)
这可能就是你想要的。
String.prototype.parseUsername = function() {
var links = [];
this.replace(/@(\w+)/g, function(all, username) {
var twitter_link = document.createElement("a");
twitter_link.href = "http://www.twitter.com/" + username;
twitter_link.target = "_blank"
links.push(twitter_link);
});
return links;
};
答案 1 :(得分:0)
这是你要找的吗?
String.prototype.parseUsername = function(userName) {
userName = this.replace(/[@]+[A-Za-z0-9-_]+/g, userName.replace("@", ""));
return (function(u) {
var twitter_link = document.createElement("a");
twitter_link.href = "http://www.twitter.com/"+u
twitter_link.target = "_blank"
console.log(twitter_link)
return twitter_link;
})(userName);
};