-
I have an array of strings and want to ensure all strings are nanoids. I was thinking about using regex, maybe there's other way. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Regexp is the only way |
Beta Was this translation helpful? Give feedback.
-
Adding examples and explanations for future reference, and newcomers. As @ai answered, RegExp is the easiest way: function verifyID(id) {
// Returns false if any character is not a word (A-Za-z0-9_) or dash (-)
return !/[^\w\-]/.test(id);
} If you know the alphabet used to make the ID, you can do the following: function verifyID(id) {
// We're expecting a string...
if(!(typeof id == 'string') || !(id instanceof String))
throw new Error("verifyID should be called as: `verifyID(id:string) → boolean`");
// We want to know what characters are being used...
let legalCharacters = (nanoid.alphabet || "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-");
// Not required. Just removes duplicate characters.
let usedCharacters = new Set(id);
// If there is an unknown character in the id, return false
for(let character of usedCharacters)
if(!(legalCharacters.includes(character)))
return false;
return true;
} |
Beta Was this translation helpful? Give feedback.
-
Since Google dropped me here, I might as well drop a faster, more robust function (for typescript specifically): type NanoID = Branded<string, "NanoID">; // Implement your own Branding type
const NANOID_LENGTH = 8; // from nanoid-dictionary
const NANOID_ALPHABET = nolookalikes;
const isNanoId = (id: unknown): id is NanoID => {
if (typeof id !== 'string') return false;
// Check if illegal chars exit
const regex = new RegExp(`^[${NANOID_ALPHABET}]{${NANOID_LENGTH}}$`);
return regex.test(id);
}; |
Beta Was this translation helpful? Give feedback.
Regexp is the only way