I'm working on an Angular application with a page where you can list candidates, see some info about them and click on the link which navigates you to candidate's web page.
I have no control over the way candidate sets his URL I can only filter invalid URLs on FE. And there is no check if URL is valid on the BE side. So I came up with a function to check it and set URL to undefined
if it's incorrect.
I'm using this REGEX:
/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm
And here is the function:
private processUrl(url: string): string {
console.log('URL:', url, 'Correct:', URL_REGEX.test(url));
console.log('URL result:', URL_REGEX.test(url) ? url : undefined);
return URL_REGEX.test(url) ? url : undefined;
}
And this is where the fun begins. Some URLs are treated as faulty even when they are correct and when you reload the page the results will change. And to make it more psychedelic first REGEX check in console.log
will treat URL as faulty and second one as correct. This is the log: (don't click on links, you'll get rick&rolled or totoed with africa)
Run 1 - init
Array(3) [ {…}, {…}, {…} ]
URL: https://www.youtube.com/watch?v=DLzxrzFCyOs Correct: true
URL result: undefined
URL: https://www.youtube.com/watch?v=VG0gwh8jwB0 Correct: false
URL result: https://www.youtube.com/watch?v=VG0gwh8jwB0
URL: blabla Correct: false
URL result: undefined
Run 2 - refresh
Array(3) [ {…}, {…}, {…} ]
URL: https://www.youtube.com/watch?v=DLzxrzFCyOs Correct: false
URL result: https://www.youtube.com/watch?v=DLzxrzFCyOs
URL: https://www.youtube.com/watch?v=VG0gwh8jwB0 Correct: true
URL result: undefined
URL: blabla Correct: false
URL result: undefined
It doesn't look like there is a problem with REGEX itself but rather with typescript misbehaving. I receive list of candidates as an array so I guess I can rule out async problems. This problem occurs without console.log()
in the function, output is same.