What's the best way to check if a URL endpoint is valid in JS?

Hey everyone! I’m trying to figure out how to check if a URL endpoint is valid using JavaScript. Specifically, I want to make sure it’s in the format of ‘/something/something’ like ‘/user/update’.

I tried using a regex pattern (/[A-Za-z0-9_.:-~/]*) but it’s not working quite right. It matches full URLs too, which isn’t what I want. I only want it to match endpoint-style strings.

Here’s a quick example of what I mean:

function isValidEndpoint(str) {
  // What regex or method should I use here?
  // It should return true for '/user/update'
  // But false for 'http://example.com/user/update'
}

console.log(isValidEndpoint('/user/update')); // Should be true
console.log(isValidEndpoint('http://example.com/user/update')); // Should be false

Any ideas on how to make this work? Thanks in advance for your help!

hey zack, heres a quick trick i use:

const isValidEndpoint = (str) => str.startsWith('/') && !str.includes('://');

it checks if the string starts with ‘/’ and doesn’t have ‘://’ (which would indicate a full URL). simple but effective for most cases. hope this helps!

Having worked on several projects involving API endpoint validation, I’ve found that a combination of regex and string methods often yields the best results. Here’s an approach that’s served me well:

function isValidEndpoint(str) {
  return /^\/[
  \w-]+(\/[\w-]+)*$/.test(str);
}

This regex ensures the string starts with a slash, followed by one or more segments separated by slashes. Each segment can contain alphanumeric characters, underscores, or hyphens. It’s strict enough to reject full URLs or invalid characters, but flexible enough to handle most endpoint structures.

In practice, I’ve found this method to be both performant and reliable. It’s caught numerous issues in our codebase before they made it to production. Just remember to pair it with server-side validation for complete security.

I’ve dealt with similar URL validation tasks before, and here’s an approach that might work for you:

function isValidEndpoint(str) {
  return /^\/[a-zA-Z0-9/]+$/.test(str);
}

This regex pattern checks if the string starts with a forward slash, followed by one or more alphanumeric characters or additional forward slashes. It won’t match full URLs or strings with other characters.

You could also consider adding more specific rules, like ensuring there’s at least one more forward slash after the initial one, depending on your exact requirements. Just remember to test thoroughly with various inputs to ensure it covers all your use cases.