Stephen K
Stephen K

Reputation: 19

Converting anything that starts with hashtag with JS. But only if over 3 characters

I've got a simple issue I just can't seem to figure out. I am converting all text that starts with a # to be a link.

Everything works fine, my issue is I want it to convert ONLY if the word that starts with # is 3 characters or more (not counting the #).

EX.

I want it to convert these to a link:

#test #cool #stackoverflow

I don't want these to convert to links:

#ok #no #m

The function that replaces the words to link is below:

function linkHashtags(text) {
    hashtag_regexp = /#([a-zA-Z0-9]+)/g;
    return text.replace(hashtag_regexp,
        '<a href="/search/$1">#$1</a>');
}

Then I call the function like this:

$('.text p').each(function () {
    $(this).html(linkHashtags($(this).html()));
});

Upvotes: 1

Views: 125

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

Use the interval operator syntax

/#([a-zA-Z0-9]{3,})/g;

{3,} basically tells it to test for 3 or more characters

Upvotes: 3

Related Questions