天天看點

使用正規表達式提取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
           

"你的指尖,擁有改變世界的力量! "

歡迎關注我的個人部落格:https://sugarat.top

js