隨著前后端的分離,用vue,react等框架在讀取內(nèi)容并顯示時(shí),因?yàn)椴辉谕粋€(gè)域名下,所以經(jīng)常需要在img的src屬性前加域名前綴,這里我們可以通過(guò)正則表達(dá)式來(lái)進(jìn)行替換
export default function imgPreSuffix(htmlString, prefix) { const regex = /<img[^>]*src="([^"]+)"[^>]*>/gi; if(htmlString){ return htmlString.replace(regex, (match, src) => { return match.replace(src, prefix + src); }); } }