Reputation: 766
I have a comment section and every comment shall be looped through and checked if there are strings in them starting with +. Those strings shall be converted to links. Butall my attempts didn't work.
HTML:
//what it actually looks like
<p class="comment">A comment with +anything</p>
<p class="comment">A comment with +anything</p>
...
//what it actually looks like
<p class="comment">A comment with <a href="anything.html">+anything</a></p>
<p class="comment">A comment with <a href="anything.html">+anything</a></p>
...
jQuery:
$(".comment").each(function() {
var comment = $(this).html();
//check if any string in 'comment' starts with plus
//get new var for the plus string(s)
//if yes append and prepend necessary code for link
//change comment to comment with modified plus strings
$(this).html(newcomment);
});
Upvotes: 0
Views: 29
Reputation: 24638
Use a regular expression, and you can even use an inline function to perform the replacement.
$(function() {
$('p').html(function(i,txt) {
return txt.replace(/\+(\w+)/g, function(match,word,ps,str) {
return '<a href="' + word + '.html">' + match + '</a>';
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="comment">A comment with +anything</p>
<p class="comment">A comment with +anything</p>
Upvotes: 0
Reputation: 101
var cmt= $(".comment");
$(cmt).each(function() {
var comment = $(this);
var plus=comment.find("a").text();
var idexof=plus.indexOf("+");
if(idexof!=0)
{
//do somthing
comment.find("a").text("anytext");
}
else
{
//do somthing
}
});
I hope it's Work for you
Upvotes: 0
Reputation: 34152
You can use a regular expression for this:
str.replace(/\+(\w+)/g, '<a href="$1.html">$1</a>');
Check the DEMO
Upvotes: 1