如何从css字符串中获取图像URL。

时间:2015-09-28 09:13:45

标签: javascript html css arrays

我遇到的问题是我想从字符串中获取图片网址。

字符串的示例是:

@media only screen and (max-width: 47.938em) { 
  .screen__start__play-btn::after { content: " "; display: block; height: 25px; position: relative; width: 100%; background-image: url(http://localhost:8080/_client/images/mouseover-line.png); background-size: cover; background-repeat: no-repeat; }
} - as a string

以下是我的代码片段:

var cssPropertiesObj = {
    mediaQuery: ['47.938em'],//media query array function get these results
    css: ['@media only screen and (max-width: 47.938em) { 
      .screen__start__play-btn::after { content: " "; display: block; height: 25px; position: relative; width: 100%; background-image: url(http://localhost:8080/_client/images/mouseover-line.png); background-size: cover; background-repeat: no-repeat; }
    }'] // get css of each media query
};


function removeUnwantedMedia(mediaQuery, css, arrayLength) {
    var startString = css.indexOf('url(');
    var endString = css.indexOf(')');

    if(css.indexOf('url(') === -1) {
        cssPropertiesObj.mediaQuery.splice(arrayLength, 1);
        cssPropertiesObj.css.splice(arrayLength, 1);
    } else {
        css.substring(startString, endString);
        console.log(css.substring(startString, endString));
    }
    console.log(css);
}
var i;
for(i = 0; i < cssPropertiesObj.mediaQuery.length; i++){
    removeUnwantedMedia(cssPropertiesObj.mediaQuery[i], cssPropertiesObj.css[i], i);
}

我期待cssPropertiesObj.css [0]在没有所有css术语的情况下等于'http://localhost:8080/_client/images/mouseover-line.png'。

这可以用JS做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用/background-image: url\((.*)\)\;/正则表达式从字符串中获取背景图片网址:

var matches = cssPropertiesObj.css[0].match(/background-image: url\((.*)\)\;/);
if (matches) {
  cssPropertiesObj.css[0] = matches[1]
}