I am trying to match hash tags and wrap them with an anchor tag.
Here is the POC:
<p class="display"></p>
var content = "I like #redApple. I have a #black hat. #red is my favorite color";
var re = /(#[a-z0-9][a-z0-9-_]*)/ig,
match, matches = [];
while (match = re.exec(content)) {
matches.push(match[1]);
}
for (i = 0; i < matches.length; i++) {
value = matches[i];
console.log(value + ".....value");
vSearch = value.replace(/[-/\^$*+?.=()|[]{}]/g, '\$&');
console.log(vSearch + ".......vSearch");
regExSearch = new RegExp(vSearch, 'g');
console.log(regExSearch + "........regExSearch");
content = content.replace(regExSearch, '<a href="#">' + value + '</a> ');
}
$(".display").append(content);
a {
color: red;
text-decoration: underline;
}
I am facing a problem: if the last hash tag word is matching any other word's first characters then its wrapping only that part of the word. For this POC, "red" is the last hash tag, that's why first "redApple" becomes "red" only. It should wrap the whole word "redApple".
Any help will be appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…