我在<p>
标记内部有一些纯文本,我试图自动查找所有链接和所有主题标签。我把我的剧本分成两部分:
我想使用纯JavaScript。什么是JS Equiv获取HTML和替换?
HTML
<p>
Thank you to @InstagramUsername for the award. I’m glad to contribute to the success of the property sector through the efforts of @AnotherUser.
#HashtagAwards #Another
</p>
JS
function getHashTags(){
// Find # and wrap in <a>
let hashTxt = document.querySelector("p")[0].html();
hashTxt = hashTxt.replace(/#(\w+)/g, "<a href='https://instagram.com/explore/tags?q=$1'>$1</a>");
hashTxt.html(hashTxt);
}
function getLinks(){
// Find @ and wrap in <a>
let linkStr = document.querySelector("p")[0].html();
linkStr = linkStr.replace(/@(\w+)/g, "<a href='https://instagram.com/$1/'>@$1</a>");
linkStr.html(linkStr);
}
function execute(){
getHashTags()
getLinks()
}
execute()
答案 0 :(得分:1)
几乎可行,您没有正确设置innerHTML
,因为hashTxt
不是元素。
function getHashTags(){
// Find # and wrap in <a>
let hashTxt = document.querySelector("p").innerHTML;
hashTxt = hashTxt.replace(/#(\w+)/g, "<a href='https://instagram.com/explore/tags?q=$1'>$1</a>");
document.querySelector("p").innerHTML = hashTxt;
}
function getLinks(){
// Find @ and wrap in <a>
let hashTxt = document.querySelector("p").innerHTML;
hashTxt = hashTxt.replace(/@(\w+)/g, "<a href='https://instagram.com/$1/'>@$1</a>");
document.querySelector("p").innerHTML = hashTxt;
}
<强>演示强>
function getHashTags(){
// Find # and wrap in <a>
let hashTxt = document.querySelector("p").innerHTML;
hashTxt = hashTxt.replace(/#(\w+)/g, "<a href='https://instagram.com/explore/tags?q=$1'>$1</a>");
document.querySelector("p").innerHTML = hashTxt;
}
function getLinks(){
// Find @ and wrap in <a>
let hashTxt = document.querySelector("p").innerHTML;
hashTxt = hashTxt.replace(/@(\w+)/g, "<a href='https://instagram.com/$1/'>@$1</a>");
document.querySelector("p").innerHTML = hashTxt;
}
function execute(){
getHashTags()
getLinks()
}
execute()
&#13;
<p>
Thank you to @InstagramUsername for the award. I’m glad to contribute to the success of the property sector through the efforts of @AnotherUser.
#HashtagAwards #Another
</p>
&#13;