如何在javascript中拉出像twitter这样的字符串 [英] how to pull @ mentions out of strings like twitter in javascript

查看:142
本文介绍了如何在javascript中拉出像twitter这样的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Node.js中编写一个应用程序,允许用户在Twitter上的消息中互相提及。我希望能够找到用户并向他们发送通知。为了做到这一点,我需要拉@usernames从node.js中的字符串中查找提及?

I am writing an application in Node.js that allows users to mention each other in messages like on twitter. I want to be able to find the user and send them a notification. In order to do this I need to pull @usernames to find mentions from a string in node.js?

任何建议,正则表达式,问题?

Any advice, regex, problems?

推荐答案

我发现这是在javascript中查找字符串内部提及的最佳方法。

I have found that this is the best way to find mentions inside of a string in javascript.

var str = "@jpotts18 what is up man? Are you hanging out with @kyle_clegg";
var pattern = /\B@[a-z0-9_-]+/gi;
str.match(pattern);
["@jpotts18", "@kyle_clegg"]

我故意将其限制为大写和小写字母数字和( - ,_)符号,以避免可能混淆像(@ j.potts)这样的用户名的句点。

I have purposefully restricted it to upper and lowercase alpha numeric and (-,_) symbols in order to avoid periods that could be confused for usernames like (@j.potts).

这是什么< a href =https://github.com/twitter/twitter-text/blob/master/js/twitter-text.js#L91\"rel =noreferrer> twitter-text.js 正在落后场景。

This is what twitter-text.js is doing behind the scenes.

// Mention related regex collection
twttr.txt.regexen.validMentionPrecedingChars = /(?:^|[^a-zA-Z0-9_!#$%&*@@]|RT:?)/;
twttr.txt.regexen.atSigns = /[@@]/;
twttr.txt.regexen.validMentionOrList = regexSupplant(
    '(#{validMentionPrecedingChars})' +  // $1: Preceding character
    '(#{atSigns})' +                     // $2: At mark
    '([a-zA-Z0-9_]{1,20})' +             // $3: Screen name
    '(\/[a-zA-Z][a-zA-Z0-9_\-]{0,24})?'  // $4: List (optional)
  , 'g');
twttr.txt.regexen.endMentionMatch = regexSupplant(/^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/);

如果你使用了更高效或更准确的东西,请告诉我。谢谢!

Please let me know if you have used anything that is more efficient, or accurate. Thanks!

这篇关于如何在javascript中拉出像twitter这样的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆