0

I'm trying to create a post having tags in between. So I'm trying to retrieve all the keyword which are followed by # using simple regex expression.

var hashtag = $('p').text().match(/#\w+\s/); console.log(hashtag); 

I'm using the .match() function to find the match of the defined regex expression, but it is only displaying one keyword, whereas I have two.

Is there any way to retrieve multiple keywords?

2
  • match isn't a "jQuery function." It's a JavaScript standard library function. jQuery is just a DOM manipulation library (plus some utilities). Commented Jul 5, 2018 at 7:55
  • .match(/#\w+\s?/g) maybe? Should be global and and the space on the end is optional? Commented Jul 5, 2018 at 8:00

2 Answers 2

2

Just pass the g flag to your regex (/#\w+\s/g):

var hashtag = $('p').text().match(/#\w+\s/g); console.log(hashtag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> This is some text that #has #hash #tags </p>

Sign up to request clarification or add additional context in comments.

4 Comments

I've tried that already. That does not help. I think the .match() function returns only single value.
@ujjwalverma That's not true. You can run the code snippet and see it working fine using match()...
this will not work as intended if I give this input : <p>#dinesh dfgdfg #ravi#xyz dfgdfg#EEE#rty gbghgf #SOLUTION</p>
I was doing something wrong at my end. Got stuck in loops. It worked though. Thanks.
1

var hashtag = $('p').text().match(/#\w*\s*/gi); console.log(hashtag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>#this is #the#text with#regular#expression hash #tags</p>

2 Comments

this will work for all possible combination of inputes
this one is much better approach. Thanks, it helped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.