Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex, searching for hashtags

How can I search some text for any and all hashtags (alphanumeric AND underscore AND hyphen) and wrap them in span tags eg search

some_string = "this is some text with 3 hashtags #Tag1 and #tag-2 and #tag_3 in it"

and convert it to:

"this is some text with 3 hashtags <span>#Tag1</span> and <span>#tag-2</span> and <span>#tag_3</span> in it"

I've got this so far:

    some_string = some_string.replace(/\(#([a-z0-9\-\_]*)/i,"<span>$1</span>");

but one fault is it doesn't include the # in the wrappings like it should. It seems to output:

"this is some text with 3 hashtags <span>Tag1</span> and #tag-2 and #tag_3 in it "

Also it only detects the first hashtag that it comes across (eg. #Tag1 in this sample), it should detect all.

Also I need the hashtags to be a minimum of 1 character AFTER the #. So # on its own should not match.

Thanks

like image 797
Sharon S Avatar asked Dec 04 '22 10:12

Sharon S


2 Answers

Try this replace call:

EDIT: if you want to skip http://site.com/#tag kind of strings then use:

var repl = some_string.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, '$1<span>$2</span>');
like image 138
anubhava Avatar answered Dec 25 '22 21:12

anubhava


This is the regular expression you want:

/(#[a-z0-9][a-z0-9\-_]*)/ig

The i makes it case insensitive, which you already had. But the g makes it look through the whole string ("g" stands for "global"). Without the g, the matching stops at the first match.

This also includes a fix to remove the incorrect parenthesis and some unneeded backslashes.

like image 21
John Fisher Avatar answered Dec 25 '22 22:12

John Fisher