I wrote a small method that evaluates JSFiddle snippet URLs.
A valid JSFiddle snippet URL looks like this: https://jsfiddle.net/BideoWego/y200sqpr/ or https://jsfiddle.net/BideoWego/y200sqpr.
An invalid URL is anything else.
It seems to work well, but for some strange reason it evaluates https://jsfiddle.net/BideoWego/ to true. How can I fix this.
JavaScript
x
9
1
// this should evaluate to false
2
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/"));
3
4
// this should evaluate to true
5
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/y200sqpr/"));
6
7
function checkCourseContentElementCodeFiddleUrl(url) {
8
return !!url.match(/((///?|https?://)?(www.)?jsfiddle.net/.+/.?([?#].*)?)/gi);
9
}
Advertisement
Answer
My solution is if the last character is /
then remove it before the regex check, so it will pass only if there’s a second parameter in the URL.
Working example
JavaScript
1
10
10
1
// this should evaluate to false
2
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/"));
3
4
// this should evaluate to true
5
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/y200sqpr/"));
6
7
function checkCourseContentElementCodeFiddleUrl(url) {
8
if (url.endsWith("/")) url = url.substring(0, url.length - 1)
9
return !!url.match(/((///?|https?://)?(www.)?jsfiddle.net/.+/.?([?#].*)?)/gi);
10
}