Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery - parse hashtags in a string using regex, except for anchors in URLs

I've looked at a couple of other possible solutions on SO but didn't see any that were doing what I was doing.

Currently I have been able to parse a string and detect hash tags with the following code:

mystring = mystring.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, "$1<span class='hash_tag'>$2</span>").replace(/\s*$/, "");

And this successfully detects all sorts of #hashtags. However it also detects anchors in URLs, such as: http://www.example.com/#anchor - I can't work out how to modify what I have to exclude anchors while keeping it flexible.

Thanks

like image 467
Martin Avatar asked Jan 29 '14 03:01

Martin


2 Answers

Here's a regex to match hashtag(#) if it has a space before it or it's beginning of string.. like so:

(^|\s)(#[a-z\d-]+)

Working regex example:

http://regex101.com/r/pJ4wC5

Javascript:

var string = '#hello This is an #example of some text with #hash-tags - http://www.example.com/#anchor but dont want the link';

string = string.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hash_tag'>$2</span>");

console.log(string);

Output:

<span class='hash_tag'>#hello</span> This is an <span class='hash_tag'>#example</span> of some text with <span class='hash_tag'>#hash-tags</span> - http://www.example.com/#anchor but dont want the link
like image 101
Bryan Elliott Avatar answered Nov 17 '22 16:11

Bryan Elliott


I know this has been answered, but if you need styling, here's a solution i used on a project:

<div id='result'>The quick brown #fox jumps over the #second  lazy dog</div>
<div id='result2'> </div>

//jquery
var str = $('#result').html(); 
var edt = str.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hash_tag'>$2</span>");

$('#result2').html(edt);




//CSS
.hash_tag {color:red;}
#result {display:none;}
like image 1
sabatino Avatar answered Nov 17 '22 15:11

sabatino