I have some strings with #prefixed words in it
For Example:
Comment 1: I am a #smart person.
Comment 2: I love to #code new things.
Comment 3: I have a #new concept.
I want it to find the #items in this strings, which I am doing with the below section.
var result = $.grep(comment.split(' '), function(item) {
var hashWords = /^#/.test(item);
return hashWords;
});
I will get each #words from the above comments with the above code
#smart
#code
#new
But I wanted it to replace to clickable links
Comment 1: I am a #smart person.
Comment 2: I love to #code new things.
Comment 3: I have a #new concept.
Please help me to figure out a solution for this as I am new to jquery.
Consider the following.
$(function() {
function replacePrefix(target) {
var regex = /\#(\w+)/gmi;
var subst = `<a href='https://www.google.com?hashtag=$1'>#$1</a>`;
var myText;
$(target).each(function(i, el) {
myText = $(el).html();
$(el).html(myText.replace(regex, subst));
});
}
replacePrefix(".comment");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="comment">I am a #smart person.</div>
<div class="comment">I love to #code new things.</div>
<div class="comment">I have a #new concept.</div>
</div>
Pass in a Selector or an Element and it will iterate over each, looking for prefixes, #new for example, and replaces them with the HTML:
<a href='https://www.google.com?hashtag=new'>#new</a>