我想用JavaScript或jQuery将#hashtag
文本替换成<a href="http://example.com/foo=hashtag"> #hasgtag</a>
文本
在这里我试着:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit #Microsoft! #facebook <a href="#link"> Somelink</a>
</p>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/#\w+\.?\w+/g,"<a href=\"http://example.com?hashtag=selectedteg\">#Selected</a> ");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
但是这个结果回来了。。。
<p id="demo">Please visit <a href="http://example.com?hashtag=selectedteg">#Selected</a> ! <a href="http://example.com?hashtag=selectedteg">#Selected</a> <a href="<a href=" http:="" example.com?hashtag="selectedteg"">#Selected</a> "> Somelink
</p>
我想结果是
<p id="demo">Please visit <a href="http://example.com?hashtag=Microsoft">#Microsoft</a> ! <a href="http://example.com?hashtag=facebook">#facebook</a> <a href="#link">Somelink</a>
</p>
最佳答案
您必须用括号捕获文本,但也必须只捕获文本,而不是html标记中的内容。请参见函数中的注释。
function hashtagReplace() {
var text = document.getElementById("demo").innerHTML;
//you have first to capture the text, to avoid the capture of #link in your example
//The text is somewhare between the start of the input, or ">" and the end of the input and "<"
var result = text.replace( /(^.|>)([^<]*)(<|.$)/g ,function(match, start, capture, end ){
//then you capture the hashtag text, and replace all the hashtag (#+hashtag_word) by the link.
//you set the text captured by the parentethis with $1
var hashtagsReplaced= (start+capture+end).replace(/\#(\w+)/g,"<a href=\"http://example.com?hashtag=$1\">#$1</a>")
//you return all the html
return hashtagsReplaced;
});
//finally you replace the html in the document
document.getElementById("demo").innerHTML = result;
}
<!DOCTYPE html>
<html>
<body>
<button onclick="hashtagReplace()">Try it</button>
<p id="demo">#Microsoft Please visit #Microsoft ! #facebook <a href="#link"> Somelink</a>
</p>
</body>
</html>