Using regex to manipulate HTML is not reliable. As @esqew pointed out, it is safer to use an HTML parser.
If you are Ok not supporting corner cases you can use this regex:
let bar = "<img src=\"/assets/img/screenshot-scripts.png\" alt=\"scripts screenshot\" class=\"half center\" /><img src=\"/assets/img/screenshot-scripts-sed.png\" alt=\"scripts sed screenshot\" />";
bar = bar.replace(/\b(src=["']?)/gi, '$1https://blog.jonesrussell.xyz');
console.log(bar);
Output:
<img src="https://blog.jonesrussell.xyz/assets/img/screenshot-scripts.png" alt="scripts screenshot" class="half center" /><img src="https://blog.jonesrussell.xyz/assets/img/screenshot-scripts-sed.png" alt="scripts sed screenshot" />
Explanation:
\b
- word boundary to reduce the chance of false positives
(src=["']?)
- expect and capture src="
, src='
, or a src=
without quotes
- in the replacement, use the captured group
$1
, and add the domain
You could use a positive lookbehind to avoid the capture group with $1
, but Safari does not yet support that.