1

I want to find hashtags in HTML by Regex.

<div class="details">
  <p>#hashtag1 #hashtag2 #hashtag3</p>
  <p>#hashtag4 #hashtag5 #hashtag6</p>
  ...
</div>

When I use this Regex:

var details = $('.details').html();
details = details.replace(/#(\S*)/g,'<a href="/?hashtag=$1">#$1</a>');
$('.details').html(details);

It returns:

<div class="details">
  <p>
    <a href="/?hashtag=hashtag1>#hashtag1</a>
    <a href="/?hashtag=hashtag2>#hashtag2</a>
    <a href="/?hashtag=hashtag3>#hashtag3</p></a>
  ...
</div>

How can I get this?

<div class="details">
  <p>
    <a href="/?hashtag=hashtag1>#hashtag1</a>
    <a href="/?hashtag=hashtag2>#hashtag2</a>
    <a href="/?hashtag=hashtag3>#hashtag3</a>
  </p>
  ...
</div>
Jeongyong Lee
  • 156
  • 1
  • 3
  • 13

2 Answers2

1

You can use this pattern /#\w+/g

var input = '<p>#hashtag1 #hashtag2 #hashtag3</p>';

console.log(input.match(/#\w+/g));

\w means: A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.


Update:

var details = $('.details').html();
details = details.replace(/#(\w+)/g,'<a href="/?hashtag=$1">#$1</a>');
$('.details').html(details);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="details">
  <p>#hashtag1 #hashtag2 #hashtag3</p>
</div>

Update 2:

var details = $('.details').html();
var pattern = /#([\p{L}\p{N}]+)/gu;

details = details.replace(pattern,'<a href="/?hashtag=$1">#$1</a>');

$('.details').html(details);

// for testing
console.log(details.match(pattern));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="details">
  <p>#nguyễn1 #nhựt2 #tân3</p>
</div>
Tân
  • 1
  • 15
  • 56
  • 102
0

@Tân gave me the answer which I wanted exactly, but I found another way to solve this problem with jQuery.

If I replace the javascript(jQuery) part like this:

var $targets = $('.details p');
$('.details p').each(function () {
  var text = $(this).text();
  text = text.replace(/#(\S*)/g,'<a href="/?hashtag=$1">#$1</a>');
  $(this).html(text);
});

This solves the problem.

Jeongyong Lee
  • 156
  • 1
  • 3
  • 13