Reputation: 4921
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
Upvotes: 0
Views: 759
Reputation: 32377
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
Upvotes: 2
Reputation: 47873
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 ]
}]
Upvotes: 4
Reputation: 6679
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("#"));
Upvotes: 2