0

the 'bg' is recognised as a variable .. its supposed to be text .. i also tried the double quotes but the url() only accepts single quotes url

            var ahref = '<a href="#" style="background-image: url('bg');"></a>';
            var newhref = ahref.replace('bg', newThumbnailUrl)

2
  • Your question is unclear. Is bg supposed to be a variable that results in a String of text? Commented Mar 31, 2021 at 20:47
  • '<a href="#" style="background-image: url(\''+bg+'\');"></a>' is foolproof. Commented Mar 31, 2021 at 20:49

1 Answer 1

1

JavaScript string interpolation works differently.

You can use Template literals, using the backtick ` `.

var bg = 'your-image.jpg';
var ahref = `<a href="#" style="background-image: url('${bg}');"></a>`;

console.log(ahref);

Or you can concatenate strings with the addition operator +.

var bg = 'your-image.jpg';
var ahref = '<a href="#" style="background-image: url(\'' + bg + '\');"></a>';

console.log(ahref);

The url() property does not require quotes, only in certain conditions.

A url, which is a relative or absolute address, or pointer, to the web resource to be included, or a data uri, optionally in single or double quotes. Quotes are required if the URL includes parentheses, whitespace, or quotes, unless these characters are escaped, or if the address includes control characters above 0x7e. source

Sign up to request clarification or add additional context in comments.

3 Comments

You may want those extra quotes like in my comment, for complex urls... but your solution should work in most cases.
@StackSlave, added. Nice catch!
thank youu that sloved my problem .. i've been searching for a solution for hours until you saved me :'( <3 thank youuu

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.