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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
ujjwal verma
  • 307
  • 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
  • 52,573
  • 26
  • 113
  • 168
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,423
  • 4
  • 19
  • 39