Use
.replace(/((?:href|src)=)(?!//example.com)(["']?)([^"']+)2/gi,
(_,x,y,z) => z.charAt(0) == '/' ?
`${x}${y}//example.com${z}${y}` : `${x}${y}//example.com/${z}${y}`)
See regex proof.
Explanation
--------------------------------------------------------------------------------
the boundary between a word char (w) and
something that is not a word char
--------------------------------------------------------------------------------
( group and capture to 1:
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
href 'href'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
src 'src'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
= '='
--------------------------------------------------------------------------------
) end of 1
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
example 'example'
--------------------------------------------------------------------------------
. '.'
--------------------------------------------------------------------------------
com 'com'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
( group and capture to 2:
--------------------------------------------------------------------------------
["']? any character of: '"', ''' (optional
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of 2
--------------------------------------------------------------------------------
( group and capture to 3:
--------------------------------------------------------------------------------
[^"']+ any character except: '"', ''' (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of 3
--------------------------------------------------------------------------------
2 what was matched by capture 2
const string = ' href="nowhere" src="/nothing.js"';
const rx = /((?:href|src)=)(?!//example.com)(["']?)([^"']+)2/gi;
console.log(string.replace(rx, (_,x,y,z) => z.charAt(0) == '/' ?
`${x}${y}//example.com${z}${y}` : `${x}${y}//example.com/${z}${y}`));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…