【发布时间】:2016-06-12 17:22:21
【问题描述】:
我正在使用 Twitter API 为我的应用获取前 5 条推文。我需要以不同的方式突出显示或链接部分推文。例如,# 将是橙色,@ 将是红色且可点击,等等...
从他们的 API 中,他们提供 user_timeline 端点:
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
但是tweets 对象的文本返回时嵌入了那些特殊字符。我看不到从对象中提取那些@, # and href 的选项:
推文对象:
{
...
text: "This is some text @tagName that I'd like to #parse here https://t.co/m9Addr4IlS",
...
}
虽然我可以编写自己的字符串解析器来查找这些内容,但 Twitter API 是否提供了一些东西来处理这些内容?
编辑:<tweets> 是一个 Angular 指令,ng-repeats 覆盖我来自 ModulesService 的推文。 replace 似乎没有附加 DOM 标签
scope.getTweets = function() {
ModulesService.getTweets().success(function(res) {
if (res && Array.isArray(res)) {
scope.tweets = parseTweets(res);
}
});
};
scope.getTweets();
var parseTweets = function (tweets) {
tweets.forEach(function (tweet) {
tweet.text.replace(/(@[^ ]+)/g, '<a class="user">$1</a>').
replace(/(#[^ ]+)/g, '<span class="hash">$1</span>').
replace(/(https?:\/\/[^ ]+)/g, '<a href="$1">$1</a>');
console.log('tweet!', tweet.text); //does not contain altered HTML
});
return tweets;
};
HTML:
<div ng-repeat="tweet in tweets" class="post-body clearfix">
{{tweet.text}}
</div>
【问题讨论】:
标签: javascript api twitter