当jg可以是jpg或png时,我需要用什么正则表达式来提取img src的一部分?我的最终结果应该是“/img.happykitten.png”或“/img.happykitten.jpg”
原始字符串的格式为“assets / img / happykitten.png”
我尝试了这个,但它不起作用:
var productImg = $('.image-holder').html(),
regex = /\/img.*(png|jpg)/,
productImgSrc = regex.exec(productImg)[0];
答案 0 :(得分:1)
答案 1 :(得分:1)
以下是JavaScript中的最小实现......
(function () {
var regex = /\.(jpg|png)$/,
images = document.getElementsByTagName('img'),
arr = [];
for (var i = 0; i < images.length; i++) {
if (regex.test(images[i].src)) {
arr = images[i].src.split('/');
console.log('/img.' + arr[arr.length - 1]);
}
}
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Images</title>
</head>
<body>
<img src="assets/img/happykitten.jpg">
<img src="assets/img/happykitten.gif">
<img src="assets/img/happykitten.svg">
<img src="assets/img/happykitten.png">
</body>
</html>