I plugged this together from various sources
<!--https://stackoverflow.com/questions/25413707/regex-for-youtube-channel-url-->
<body>
<button onclick="writeytElement()">YTID</button>
<script>
function writeytElement() {
//document.write("<div>Let's print an additional DIV here</div>");
let str = 'https://www.youtube.com/user/SaphiraLynx';
let pattern = '/(https?:\/\/)?(www\.)?youtu((\.be)|(be\..{2,5}))\/((user)|(channel))\/?([a-zA-Z0-9\-_]{1,})/';
let matchs = str.match(pattern);
matchs[9];
document.write("<div>matchs</div>");
}
</script>
</body>
<!---pregmatch(UC[-_0-9A-Za-z]{21}[AQgw]);-->
<!--https://stackoverflow.com/questions/14366648/how-can-i-get-a-channel-id-from-youtube?rq=1-->
However it seems to malfunction. I.e. /no output/
Is this an issue of mine, or of the code (see commented section(s) ? (I might have mangled the variable in the document.write ...
But the script won't work still
CodePudding user response:
The issue is likely with the regex pattern, as it won't match the given string. Try using this regex instead:
/(https?:\/\/)?(www\.)?youtube\.com\/(channel|user)\/([a-zA-Z0-9\-_]{1,})/
CodePudding user response:
Remove the quotes from the pattern. Without quotes, it is a regex literal. With quotes, it is simply a string.
let str = 'https://www.youtube.com/user/SaphiraLynx';
// wrong
let pattern1 = '/(https?:\/\/)?(www\.)?youtu((\.be)|(be\..{2,5}))\/((user)|(channel))\/?([a-zA-Z0-9\-_]{1,})/';
let matchs1 = str.match(pattern1);
console.log(matchs1);
// right
let pattern2 = /(https?:\/\/)?(www\.)?youtu((\.be)|(be\..{2,5}))\/((user)|(channel))\/?([a-zA-Z0-9\-_]{1,})/;
let matchs2 = str.match(pattern2);
console.log(matchs2);
Also, if you want to embed variables within a string, consider using template literals:
document.write(`<div>${matchs}</div>`);