感谢您在问题中添加示例链接,它真的很有帮助。我已经删除了之前混乱的尝试。
var items = document.getElementsByClassName('post-list-content-element');
[].forEach.call(items, function(item){
item.innerHTML = item.innerHTML.replace(
/http?:\/\/\S*?\.(jpg|png|gif)/g,
'<img src=$&>');
});
一个提示:假设您的
post-list-content-element
div中没有实际图像。
好的,这里有一个更通用的版本,它只在文本节点内进行替换。 我将让您自行解决错误 :-)
var replaceInChildTextNodes = (function(){
var eachChild, splits;
eachChild = function(node, f){
var children, parent = node;
children = [].slice.apply(parent.childNodes);
children.forEach(function(child){
f(child, parent);
eachChild(child, f);
});
};
splits = function(s, regexp){
var nonmatches=[], matches=[], i=0, j=0;
while((match = regexp.exec(s))){
j = match.index;
nonmatches.push(s.substr(i, j-i));
matches.push(match[0]);
i = j + match[0].length;
if(!regexp.global)
break;
}
nonmatches.push(s.substr(i));
return {nonmatches: nonmatches, matches: matches};
};
return function(nodes, regexp, replacer){
[].forEach.call(nodes, function(node){
eachChild(node, function(childNode, parent){
var match, i=0, j=0, split, newNodes=[];
if(childNode.nodeName === '#text'){
split = splits(childNode.nodeValue, regexp);
if(split.matches.length === 0)
return;
newNodes = [];
split.nonmatches.forEach(function(text, i){
if(text !== '')
newNodes.push(document.createTextNode(text));
if(split.matches[i])
newNodes.push(replacer(split.matches[i]));
});
newNodes.forEach(function(newNode){
parent.insertBefore(newNode, childNode);
});
parent.removeChild(childNode);
}
});
});
};
}());
使用方法:
var parents = document.getElementsByClassName('post-list-content-element');
replaceInChildTextNodes(parents, /http?:\/\/\S*?\.(jpg|png|gif)/g, function(text){
var img = document.createElement('img');
img.src = text;
return img;
});
该方法不使用String#split,因此您不需要担心在正则表达式中捕获组,并且它遵守g
标志。
注意:不跨浏览器。
<a>
标签)还是原始URL文本? - Brock Adams