check if a string is a salesforce id

Anyone have a good way to perform a check on a string to see if it is a salesforce id, beyond ensuring that it’s 18 characters long?

I think the first 3 characters are the object ID, so you could check to make sure the string has 18 characters and begins with a 3 character string that matches one of the objects you are receiving these id’s from.

Are you checking just a string itself, or is there metadata available that you could also check (checking for field type, for example)?

Hmm, that might work, Raymond… but to make the solution portable between orgs I’m going to have to dynamically get the first three characters of the objects in question. Is there a simple way to do that beyond building a model on the object to query it and check the id?

Here’s what I’m doing right now. It’s obviously not foolproof, but should work 99% of the time for our use case.

string.length === 18 && string.match(/[A-Za-z0-9]/)