如何使用 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 编写(因为您的问题并不意味着您使用任何库,例如 jquery ):
// 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);
}
});
})();
这应该放在收盘前 </body>
标签;以便在 DOM 构建完成后运行。
引用文献:
关于javascript - 使用 Javascript 删除和更改 HTML 中 URL 的某些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583883/