我正在尝试编写一个函数,该函数将接受一个字符串,对其进行解析,然后将图像 url 替换为 a<img src="image">
并将链接替换为<a href="link">link</a>
.
这就是我所做的:
var __urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var __imgRegex = /^ftp|http|https?:\/\/(?:[a-z\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png)$/ig;
function parseURL($string){
var exp = __urlRegex;
return $string.replace(exp,function(match){
if(__imgRegex.test(match,contents)){
return '<img src="'+contents+'" width="200" />';
}
else{
return '<a href="'+contents+'" target="_blank">'+contents+'</a>';
}
}
);
}
当我进行一些测试时,正则表达式工作正常。然而,在实施过程中,会发生一些奇怪的胡言乱语。如果我向它抛出说 5 个图像 url,它会将第一个解析为图像,而将第二个解析为链接,然后交替进行!
我哪里错了?
我用于测试的示例字符串:
This is a kitten http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
with a sibling which is also a kitten http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
and a sister which is also a kitten http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
and lots of kittens
http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg
这是我得到的输出
<p>This is a kitten <img src="http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg" width="200">
with a sibling which is also a kitten <a href="http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg" target="_blank">http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg</a>
and a sister which is also a kitten <img src="http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg" width="200">
and lots of kittens
undefined
<img src="http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg" width="200">
<a href="http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg" target="_blank">http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg</a>
<img src="http://s3.amazonaws.com/rapgenius/filepicker%2FvCleswcKTpuRXKptjOPo_kitten.jpg" width="200"></p>