-
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.
Answered by
ai
Mar 8, 2023
Replies: 2 comments 2 replies
-
Regexp is the only way |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
lsuarezj
-
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.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regexp is the only way