Skip to content
Advertisement

JsFiddle URL with trailing slash being evaluated as correct link

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.

// this should evaluate to false
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/"));

// this should evaluate to true
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/y200sqpr/"));

function checkCourseContentElementCodeFiddleUrl(url) {
    return !!url.match(/((///?|https?://)?(www.)?jsfiddle.net/.+/.?([?#].*)?)/gi);
  }

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

// this should evaluate to false
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/"));

// this should evaluate to true
console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/y200sqpr/"));

function checkCourseContentElementCodeFiddleUrl(url) {
  if (url.endsWith("/")) url = url.substring(0, url.length - 1)
  return !!url.match(/((///?|https?://)?(www.)?jsfiddle.net/.+/.?([?#].*)?)/gi);
}
Advertisement