【问题标题】:How can I get JQuery to replace the non URL parts of the string when fetching the background images url获取背景图像 url 时如何让 JQuery 替换字符串的非 URL 部分
【发布时间】:2020-02-20 14:23:44
【问题描述】:

我有这段代码可以提取背景图像的元素,但是它也提取了代码的“url”部分。我只需要实际的图片地址

我尝试使用替换功能,但是当我检查输出时它对字符串没有任何作用。

var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);

元素内的图像是 //imageaddress.jpg 所以它把它提取为

https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)

我怎样才能解决这个问题,这样它就可以给我

https://example.com/sites/image.jpg?itok=jfzYQHZx

【问题讨论】:

  • .+ 匹配除换行符以外的任何字符,替换为[^()]+ 以避免匹配括号。更好,使用[^()"']+
  • 能把jQuery('#block-content').css('background-image')的内容发一下吗
  • 看起来像<div class="intro-image media_27796" style="background-image: url('//example.com/sites/g/files/awvsbl221/files/styles/intro_homepage/public/image.jpg?h=c9aba1c0&itok=siFmAXu7');">   </div>

标签: javascript jquery regex


【解决方案1】:

请注意,某些 URL 并不总是在引号中:

url(https://example.com/sites/image.jpg?itok=jfzYQHZx)

然后添加['"]? => ? 检测到零或1个字符

var str  = "url('https://example.com/sites/image.jpg?itok=jfzYQHZx')"; // example string
var str2 = "url(https://example.com/sites/image.jpg?itok=jfzYQHZx)"; // without quotes
str  = str.replace(/^url\(["']?(.+?)["']?\)/,"$1"); // replace with first group (.+?)
str2 = str2.replace(/^url\(["']?(.+?)["']?\)/,"$1"); 
console.log(str);
console.log(str2);
var jsonData = { "image": jQuery('#block-content').css('background-image').replace(/^url\(["']?(.+?)["']?\)/,"$1"),}

【讨论】:

    【解决方案2】:

    用这个替换图像属性

     "image": jQuery('#block-content').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""),
    

    【讨论】:

      【解决方案3】:

      希望对你有所帮助。

      var tmp = 'https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)';
      tmp = tmp.substring(tmp.indexOf("(h") + 1);
      tmp = tmp.substring(0, tmp.length - 1);
      console.log(tmp);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多