Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  140] [ 1]  / answers: 1 / hits: 20435  / 11 Years ago, wed, january 29, 2014, 12:00:00

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-zd][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


More From » jquery

 Answers
24

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



(^|s)(#[a-zd-]+)


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-zd-]+)/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

[#72879] Tuesday, January 28, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cindyanyssam

Total Points: 483
Total Questions: 94
Total Answers: 100

Location: Barbados
Member since Sat, May 28, 2022
2 Years ago
;