Instead of replacing all unwanted parts of a string, just use the regex to fetch the part you need. This uses regex much more effectively, as you don't need to make any assumptions on the source string, or make any other modifications before you set the attribute. This is all the code you need:
string = $(".ytp-cued-thumbnail-overlay").css('background-image');
$("#img1").attr('src', string.match(/.*url\(['|"]([^)]*)['|"]\)/i));
And here's a demonstration (using the same regex, but different code to better illustrate the process):
string = $("#source").text();
$("#match").text(string.match(/.*url\(['|"]([^)]*)['|"]\)/i)[1]);
#source, #match { display:inline-block;border:1px solid #aaa;padding:10px; }
#source:before { color:#aaa;content:'source: '; }
#match:before { color:#aaa;content:'match: ';}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="source">url("this is your URL")</div>
→
<div id="match"></div>
Why matching is superior to modifying the string
In comparison to methods that will get whatever value css()
returns, this will return null
if no match was found, which you can check for in your implementation. For example, if your background-image value is http://www.example.com
and you chop the first five and last two characters, expecting it to actually say url("http://www.example.com/img.png")
, you will get //www.example.c
, which doesn't make for a very nice URL.