How to extract Twitter usernames from a tweet using Javascript

一个人想着一个人 提交于 2020-01-05 08:54:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!