Home » Jquery » javascript – How can I get the background image URL in Jquery and then replace the non URL parts of the string

javascript – How can I get the background image URL in Jquery and then replace the non URL parts of the string

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have this code which extracts the element for the background image, however it pulls in the ” url’ ” parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn’t do anything to the string when i check the output.

    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);

The image inside the element is //imageaddress.jpg so it’s extracting it as

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

How can i fix this so that it just gives me https://example.com/sites/image.jpg?itok=jfzYQHZx

Thanks

How to&Answer:

If your background image path is not contained in quotes, your expression failes. Add a question mark behind your quote capturing to make it optional.

Your expression would look like this: ^url([\”\’]?(.+)[\”\’]?).