1

I have my html

<div class="comment-details">Hello @samplename This is my comment</div>
...
...
More .comment-details elements

On page load, I wanted to find this @samplename inside .comment-details class using .each() loop and insert it on <a href="samplelink"></a> tag in jQuery or Javascript

I wanted something like this after page load:

<div class="comment-details">Hello <a href="samplelink">@samplename</a> This is my comment</div>
Mark Salvania
  • 486
  • 3
  • 17

2 Answers2

2

jQuery implementation:

$('.comment-details').each(function(){
    $(this).html($(this).html().replace(/\@.+?\b/g, `<a href=profile/${$(this).html().match(/\@.+?\b/g)[0].replace('@','')}>${$(this).html().match(/\@.+?\b/g)}</a>`));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-details">Hello @samplename This is my comment</div>
<div class="comment-details">Hello @JG This is my comment</div>

enter image description here

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
1

In raw JS you can do

[...document.querySelectorAll('.comment-details')]
.forEach(tag => {
  tag.innerHTML = tag.innerHTML
    .replace(/\s?@(\w+)\s?/g, ' <a href="https://twitter.com/$1">@$1</a> ')
})
<div class="comment-details">Wow @m0meni great answer</div>
<div class="comment-details">@m0meni a little self-congratulatory though</div>

Explaining each step:

  • querySelectorAll grabs all the comment details divs
  • [...] is because of In Javascript, what is the best way to convert a NodeList to an array
  • then you use the string replace function with a regular expression to do what you want
    • /\s?@(\w+)\s?/g grabs all the characters after @, and only does it if there's a space/nothing on either side i.e. hi@potoato wouldn't be matched
    • the $1 in the second argument uses the match from the replace
m0meni
  • 16,006
  • 16
  • 82
  • 141