開發中遇到需要匹配htmk字符串中包含的所有img src的值,要用正則表達式去匹配出來,用在線正則測試工具測試,/<img [^>]*src=['"]([^'"]+)[^>]*>/,可以匹配到html中的src值,但是用在js上輸出的結果卻是:
<img src="http://static.cnblogs.com/images/logo_small.gif" alt="" width="142" height="55" />
將整個html的標簽都給返回了回來,這樣很麻煩,與期望的 http://static.cnblogs.com/images/logo_small.gif
並不一致。
看到一篇博客,講到
content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match) {
console.log(match);
});
function中並不止有match一個參數,還有其他參數,capture
content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
console.log(capture);
});
capture輸出就是我想要的結果
參考博客來源者:博客園@dudu