今天開發中遇到一個問題:如何替換一段HTML字符串中包含的所有img標簽的src值?
開始想到的解決方法是:
content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match) { console.log(match); });
輸出結果是:
<img src="http://static.cnblogs.com/images/logo_small.gif" alt="" width="142" height="55" />
得到的是整個img標簽,但我期望得到的是src中的網址,這樣只需在function(match)中返回新地址就行了。
於是,卡在這里了。。。
后來,通過Google搜索關鍵字“javascript replace callback”,在stackoverflow中找到了“replace callback function with matches”,才知道function(match)還有其他參數(詳見developer.mozilla.org)。
然后,改為下面的代碼,問題就解決了。
content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) { console.log(capture); });
輸出結果:
http://static.cnblogs.com/images/logo_small.gif
搞定!