javascript - 使用 Javascript 删除和更改 HTML 中 URL 的某些文本

标签 javascript html

如何使用 Javascript 删除和更改 HTML 中 URL 的某些文本。

例如,我的 HTML 中有这张 Instagram 照片。

<img src="http://scontent-b.cdninstagram.com/hphotos-xaf1/t51.2885-15/10611172_606838796104009_200732638_s.jpg">

然后我希望它能够自动链接(通过 javascript)到此处的较大图像预览: http://scontent-b.cdninstagram.com/hphotos-xaf1/10611172_606838796104009_200732638_n.jpg

请注意,_s 已更改为 _n,并且 URL 中的文件夹/t51.2885-15 已被删除。

所以基本上我只想要一个javascript来删除/t51.2885-15并用_n替换_s。

我认为这可以使用 javascript 来实现,但我不知道为什么。几行代码就能轻松写出这个吗?或者除了编写 JavaScript 之外您还有其他建议吗?

最佳答案

我建议,用纯 JavaScript 编写(因为您的问题并不意味着您使用任何库,例如 ):

// wrapped the function as an 'Immediately-Invoked Function Expression' (IIFE)
// so that it'll be called automatically, when encountered:
(function () {
// gets all the images on the page:
    var images = document.querySelectorAll('img'),
// creates an '<a>' element:
        link = document.createElement('a'),
// creates a variable (for later use, within the 'forEach()'):
        newLink;

// uses 'Array.prototype.forEach()' to iterate over the images:
    [].forEach.call(images, function (img) {

    // checks that 'instagram.com' is in the 'src' of the current image:
        if (img.src.indexOf('instagram.com') > -1) {
            // if it is, we clone the created-'a' element:
            newLink = link.cloneNode();

            // set the 'href' of the '<a>' to the 'src' of the image,
            // but first we replace '_s' with '_n', and
            // any sequence of characters starting with a '/' followed by
            // 't51' continuing with alphanumeric characters (a-z, 0-9,
            // case-insensitive) periods ('.') or hyphens ('-') with an
            // empty string (removing that sequence from the 'src'):
            newLink.href = img.src.replace(/(_s)|(\/t51[\w\d.-]+)/g,function (match){
                return match === '_s' ? '_n' : '';
            });

            // insert the '<a>' element before the image:
            img.parentNode.insertBefore(newLink,img);
            // move the image into the '<a>':
            newLink.appendChild(img);
        }
    });
})();

JS Fiddle demo .

这应该放在收盘前 </body>标签;以便在 DOM 构建完成后运行。

引用文献:

关于javascript - 使用 Javascript 删除和更改 HTML 中 URL 的某些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583883/

相关文章:

html - 如何在 HTML 上打印代码

jquery - 倒数计时器的一个不错的选择 - 将 "0"放在个位数前面

javascript - 一个纯 CSS 文本链接到视频 slider

javascript - doT.js 模板中的全局辅助函数

html - Angular 2 格式日期时间问题

javascript - 无法显示 JavaScript 小部件

javascript - 使用 JQuery Mobile 按钮触发 Rest API 调用

javascript - 如何使用 JavaScript 防止 Adob​​e Livecycle 中出现重复的验证消息

php - 使用 jQuery 自动 PHP 通知

javascript - 选项卡式内容加载速度非常慢