0

I recently built a small app for my site that allows my users to display their tweets. I am wondering if their is a way with jQuery or Javascript to detect or find stuff like hashtags and http://'s ?

A simple example of a sentence might be:

The quick #brown fox jumps over the #lazy dog
ApPeL
  • 4,801
  • 9
  • 47
  • 84

3 Answers3

4

You might give twitter-text-js a try. It can do things like auto link @mentions, #hashtags, and urls.

twttr.txt.autoLink('A @screen_name, #hashtag, and url: http://twitter.com autolinked')

Will result in:

"A @<a class="tweet-url username" data-screen-name="screen_name" href="http://twitter.com/screen_name" rel="nofollow">screen_name</a>, <a href="http://twitter.com/search?q=%23hashtag" title="#hashtag" class="tweet-url hashtag" rel="nofollow">#hashtag</a>, and url: <a href="http://twitter.com" rel="nofollow" >http://twitter.com</a> autolinked"

Or finding the indices of #hashtags:

twttr.txt.extractHashtagsWithIndices('A @screen_name, #hashtag, and url: http://twitter.com autolinked')

will result in:

[{
  hashtag: "hashtag",
  indices: [ 16, 24 ]
}]
abraham
  • 46,583
  • 10
  • 100
  • 152
2

You can use a regex to match a part of the string

hashtags = /\#\w+/g.exec( "The quick #brown fox" );

See it working at https://regex101.com/r/pai19N/1

trincot
  • 317,000
  • 35
  • 244
  • 286
Paul Alexander
  • 31,970
  • 14
  • 96
  • 151
  • thanks so much, although when running it through jQuery it only picks up the first one, even if there are more hashtags in the "string" any idea why? – ApPeL Apr 21 '11 at 10:24
  • You'll need to call exec multiple times to get all the matches. – Paul Alexander Apr 23 '11 at 15:49
2

Javascript's .search() method will give you the index in a string that your character occurs:

<p id="mystring">Hello, how are #you today?</p>

alert($("#mystring").html().search("#"));
Jesse Bunch
  • 6,651
  • 4
  • 36
  • 59