how do I find a # with jQuery?

766 Views Asked by At

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
3

There are 3 best solutions below

0
On BEST ANSWER

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 ]
}]
2
On

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

1
On

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("#"));