document.querySelector不是一个函数 - 试图用社交包装器替换#和链接

时间:2018-04-16 09:21:26

标签: javascript regex

我在<p>标记内部有一些纯文本,我试图自动查找所有链接和所有主题标签。我把我的剧本分成两部分:

  1. 首先应用hashtag wrapper
  2. 然后应用链接包装器
  3. 执行功能将运行上述两个功能
  4. 我想使用纯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()
    

1 个答案:

答案 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;
}

<强>演示

&#13;
&#13;
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;
&#13;
&#13;