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?

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
ujjwal verma
  • 309
  • 3
  • 10
  • `match` isn't a "jQuery function." It's a JavaScript standard library function. jQuery is just a DOM manipulation library (plus some utilities). – T.J. Crowder Jul 05 '18 at 07:55
  • `.match(/#\w+\s?/g)` maybe? Should be global and and the space on the end is optional? – Eddie Jul 05 '18 at 08:00

2 Answers2

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>
BenM
  • 51,470
  • 24
  • 115
  • 164
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>
Dinesh Ghule
  • 3,277
  • 4
  • 22
  • 38