使用正則表達式提取background:url()中的內容


開發中經常碰見元素使用background或者background-imgae等樣式表提供的屬性來展示圖片而不是img使用標簽,在修改的時候就會發現弊端在需要動態修改圖片的時候沒有img.src那樣順手,簡單的法子就是提取出元素的background屬性,然后使用substr字符傳截取獲取到的值,馬虎的思考一下這確實沒問題,但是真這樣做了之后就發現了一個問題(說的正式在下😄),不同瀏覽器下面同樣的代碼獲取到的結果不一致

反例

<div id='test' style='background:url(https://www.baidu.com/img/bd_logo1.png) 200px 100px;width:200px;height:100px'></div>
document.querSelector('#test').style.background

chrome

url("https://www.baidu.com/img/bd_logo1.png") 200px 100px

firefox

rgba(0, 0, 0, 0) url("https://www.baidu.com/img/bd_logo1.png") repeat scroll 200px 100px

其它內核手頭暫時沒有,沒有測試,使用傳統的substr肯定是行不通了,接下來只有使用正則表達式去解決了

如果使用style.backgroundImage這兩瀏覽器獲取到的值就會是一樣的了

下面是使用正則表達式去獲取目標內容

第一步

匹配出url(xxxx)使用/url\("?'?.*"?'?\)/g

let reg = /url\("?'?.*"?'?\)/g
'rgba(0, 0, 0, 0) url("https://www.baidu.com/img/bd_logo1.png") repeat scroll 200px 100px'.match(reg)
// ['url("https://www.baidu.com/img/bd_logo1.png")']
'url(https://www.baidu.com/img/bd_logo1.png)'.match(reg)
// ['url("https://www.baidu.com/img/bd_logo1.png")']

第二步

剔除不相關的內容,/"|'|url|\(|\)/g

let reg = /"|'|url|\(|\)/g
'url("https://www.baidu.com/img/bd_logo1.png")'.replace(reg,'')
// https://www.baidu.com/img/bd_logo1.png

最終

綜合前面的例子

function getBackgroundUrl(background){
  let regBackgroundUrl = /url\("?'?.*"?'?\)/g;
  let regReplace = /"|'|url|\(|\)/g;
  return background.match(regBackgroundUrl)[0].replace(regReplace,'')
}

console.log(getBackgroundUrl('rgba(0, 0, 0, 0) url("https://www.baidu.com/img/bd_logo1.png") repeat scroll 200px 100px'))
// https://www.baidu.com/img/bd_logo1.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM