Skip to content

Latest commit

 

History

History
25 lines (19 loc) · 655 Bytes

check-if-a-string-is-a-mongo-db-object-id.mdx

File metadata and controls

25 lines (19 loc) · 655 Bytes
category created title updated
Validator
2021-04-10
Check if a string is a MongoDB ObjectId
2021-10-13

JavaScript version

const isMongoId = (str) => str.length === 24 && /^[A-F0-9]+$/i.test(str);

// Or
const isMongoId = (str) => str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);

TypeScript version

const isMongoId = (str: string): boolean => str.length === 24 && /^[A-F0-9]+$/i.test(str);

// Or
const isMongoId = (str: string): boolean =>
    str.length === 24 && str.split('').every((c) => '0123456789ABCDEFabcdef'.indexOf(c) !== -1);