Regex for a valid hashtag

I need regular expression for validating a hashtag. Each hashtag should starts with hashtag(“#”).

Valid inputs:

1. #hashtag_abc

2. #simpleHashtag

3. #hashtag123

Invalid inputs:

1. #hashtag#

2. #[email protected]

I have been trying with this regex /#[a-zA-z0-9]/ but it is accepting invalid inputs also.

Any suggestions for how to do it?

Answer

There are 2 issues:

You might also need anchors (^ / $) if you want to have a full string match.

Use

/^#w+$/

See the regex demo.

Leave a Reply

Your email address will not be published. Required fields are marked *