Regular expression to add a string

62 views Asked by At

I have the string src="//www.youtube.com/embed/9w6YSZ_o7rA" where the URL could be anything, and I want to add ?autoplay=1 at the end, so I'll have:

src="//www.youtube.com/embed/9w6YSZ_o7rA?autoplay=1"

Could someone recommend a clean regex expression to use with JavaScript str.replace()?

2

There are 2 answers

2
CrayonViolent On BEST ANSWER

This doesn't require regex.

edit: updated to account for possible fragment (though It's n/a for youtube urls)

src = src.split('#');
src[0]+= (src[0].indexOf('?')>-1) ? '&' : '?';
src[0]+= 'autoplay=1';
src = src.join('#');
4
aelor On
str.replace(/(.*)/,'$1?autoplay=1');

this should help you