问题
I want to use Javascript to parse a tweet and return an array containing the people mentioned in that tweet. Twitter usernames all begin with @. Assuming that I already have the string, how can this be done?
回答1:
var tweet = "hello to @you and @him!";
var users = tweet.match(/@\w+/g);
console.log(users); // Will return an array containing ["@you", "@him"]
Then, you can strip the @
to only get the names:
for (userIndex = 0; userIndex < users.length; userIndex++)
users[userIndex] = users[userIndex].substr(1);
Which will then return the array as
["you", "him"]
回答2:
var tweet = 'This tweet is for @me and @you #hashtag';
var matches = tweet.match(/@\w+/g);
http://jsfiddle.net/9QLbb/
来源:https://stackoverflow.com/questions/9665279/how-to-extract-twitter-usernames-from-a-tweet-using-javascript