如何使用Javascript从推文中提取Twitter用户名

时间:2012-03-12 10:21:21

标签: javascript string parsing twitter

我想使用Javascript来解析推文并返回一个包含该推文中提到的人的数组。 Twitter用户名都以@开头。假设我已经有了字符串,怎么办呢?

2 个答案:

答案 0 :(得分:5)

var tweet = "hello to @you and @him!";
var users = tweet.match(/@\w+/g);
console.log(users); // Will return an array containing ["@you", "@him"]

然后,您可以删除@以仅获取名称:

for (userIndex = 0; userIndex < users.length; userIndex++)
    users[userIndex] = users[userIndex].substr(1);

然后将数组作为

返回
["you", "him"]

答案 1 :(得分:1)

​var tweet = 'This tweet is for @me and @you #hashtag';
var matches = tweet.match(/@\w+/g);

http://jsfiddle.net/9QLbb/

相关问题