简体   繁体   English

JavaScript / jQuery处理然后替换我HTML内容中的所有链接

[英]JavaScript/jQuery manipulate and then replace all links in my HTML content

I am trying to write a script that, after the page load, will replace all my existing links with links in a different format. 我正在尝试编写一个脚本,该脚本在页面加载后将所有现有链接替换为其他格式的链接。

However, while I've managed to work out how to do the link string manipulation, I'm stuck on how to actually replace it on the page. 但是,尽管我设法解决了链接字符串操纵的问题,但是我仍然停留在如何在页面上实际替换它的工作上。

I have the following code which gets all the links from the page, and then loops through them doing a regular expression to see if they match my pattern and then if they do taking out the name information from the link and creating the new link structure - this bit all works. 我有以下代码,该代码从页面获取所有链接,然后遍历它们进行正则表达式,以查看它们是否与我的模式匹配,然后从链接中提取名称信息并创建新的链接结构-这一切工作。 It's the next stage of doing the replace where I'm stuck. 这是进行替换的下一个阶段。

var str;
var fn;
var ln;
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {

    str = links[i].href.match(/\/Services\/(.*?)\/People\/(.*?(?=\.aspx))/gi);

    if (links[i].href.match(/\/Services\/(.*?)\/People\/(.*?(?=\.aspx))/gi)) {
        var linkSplit = links[i].href.split("/");

        // Get the last one (so the .aspx and then split again).
        // Now split again on the .
        var fileNameSplit = linkSplit[linkSplit.length-1].split(".");

        var nameSplit = fileNameSplit[0].split(/(?=[A-Z])/);

        fn = nameSplit[0];
        ln = nameSplit[1];
        if(nameSplit[2]){
            ln += nameSplit[2];
        }

        // Build replacement string
        var replacementUrl = 'https://www.testsite.co.uk/services/people.aspx?fn='+fn+'&sn='+ln;

        // Do the actual replacement
        links[i].href.replace(links[i].href, replacementUrl);
    }

I've tried a couple of different solutions to make it do the actual replacement, .replace, .replaceWith, and I've tried using a split/join to replace a string with an array that I found here - Using split/join to replace a string with an array 我尝试了几种不同的解决方案以使其进行实际替换,.replace,.replaceWith,并且尝试使用拆分/连接将字符串替换为在此处找到的数组- 使用拆分/连接以用数组替换字符串

var html = document.getElementsByTagName('html')[0];
var block = html.innerHTML;
var replace_str = links[i].href;
var replace_with = replacementUrl;

var rep_block = block.split(replace_str).join(replace_with);

I've read these, but had no success applying the same logic: 我读过这些,但是应用相同的逻辑没有成功:

How can I fix this problem? 我该如何解决这个问题?

比这更简单:

links[i].href = replacementUrl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM