// 注意,我使用了\w 来匹配图片名,表示匹配[A-Za-z0-9_]之内的字符都能被匹配到
// 另外最后我使用一个表达式来限定只匹配图片后缀
console.log(img.src.match(/\/(\w+\.(?:png|jpg|gif|bmp))$/i)[1])
<!DOCTYPE HTML><html>
<head>
<title>Page Title</title>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
<script>
onload = function (){
var html = document.body.innerHTML
var reg = /(<img(?:(?!id|>).)*)(id[\=\"\'\s]+)?([^\"\'\s]*)([\"\']?)([^>]*>)/gi
var idx = 0
html = html.replace(reg, function($0, $1, $2, $3, $4, $5){
idx++
if(typeof $2 == "undefined"){
return $1 + " id='" + idx + "'" + $3 + $4 + $5
}
return $1 + $2 + idx + $4 + $5
})
document.body.innerHTML = html
}
</script>
</head>
<body>
<img src="acb.jpg" id="imgx" />
<ul>
<li><img src="sdf.png" /></li>
</ul>
</body>
</html>
<html><head>
<!--
将此内容保存为 html 文件,浏览器允许运行脚本进行测试。
-->
<script type="text/javascript">
function check()
{
var str
str = document.getElementById("txtInput").value
alert("替换结果:" + str.replace(/<img[^>]+img\/([^>"]*)"[^>]+\/>/, "$1"))
}
</script>
</head>
<body>
输入:<input type="text" id="txtInput" value='xxxx <img src="img/fxxx.png" /> xxxx' />
<button type="button" onclick="check()">正则替换</button>
</form>
</body>
</html>