const regex = /(?<=(?:\[embed\])|(?:\[embed\]\s)|(?:))(https?:\/\/)(:?www\.)?(:?youtube\.com\/watch|youtu\.be\/)([\w\?=\&]+)(?=(?:\[\/embed\])|(?:\s\[\/embed\])|(?:))/gims;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<=(?:\\[embed\\])|(?:\\[embed\\]\\s)|(?:))(https?:\\\/\\\/)(:?www\\.)?(:?youtube\\.com\\\/watch|youtu\\.be\\\/)([\\w\\?=\\&]+)(?=(?:\\[\\\/embed\\])|(?:\\s\\[\\\/embed\\])|(?:))', 'gims')
const str = `bla https://www.youtube.com/watch?v=Vpg9yizPP_g
http://www.youtube.com/watch?v=Vpg9yizPP_g bla
[embed]https://www.youtube.com/watch?v=Vpg9yizPP_g[/embed] bla
[embed] https://www.youtube.com/watch?v=Vpg9yizPP_g [/embed]
[embed]http://www.youtube.com/watch?v=Vpg9yizPP_g[/embed]
[embed] http://www.youtube.com/watch?v=Vpg9yizPP_g [/embed]
bla https://youtube.com/watch?v=Vpg9yizPP_g bla
http://youtube.com/watch?v=Vpg9yizPP_g
[embed]https://youtube.com/watch?v=Vpg9yizPP_g[/embed]bla
bla[embed] https://youtube.com/watch?v=Vpg9yizPP_g [/embed]
[embed]http://youtube.com/watch?v=Vpg9yizPP_g[/embed]
[embed] http://youtube.com/watch?v=Vpg9yizPP_g [/embed]
https://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g
http://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g
[embed]https://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
[embed] https://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]
[embed]http://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
bla[embed] http://www.youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]bla
https://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g bla
bla http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g
[embed]https://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
[embed] https://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]
[embed]http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g[/embed]
[embed] http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g [/embed]
https://youtu.be/Vpg9yizPP_g
http://youtu.be/Vpg9yizPP_g bla
[embed]https://youtu.be/Vpg9yizPP_g[/embed]
[embed] https://youtu.be/Vpg9yizPP_g [/embed]
[embed]http://youtu.be/Vpg9yizPP_g[/embed]
[embed] http://youtu.be/Vpg9yizPP_g [/embed]
<a href src="http://youtu.be/Vpg9yizPP_g">vid</a>
<a href src="http://youtube.com/watch?feature=player_embedded&v=Vpg9yizPP_g">vid</a>
<a href src="https://youtube.com/watch?v=Vpg9yizPP_g">vid</a>`;
const subst = `\1\2\3\4`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions