Skip to content

Instantly share code, notes, and snippets.

@devbanana
Last active September 23, 2021 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devbanana/812e2a06e77ba15d19eaf2344ebe7861 to your computer and use it in GitHub Desktop.
Save devbanana/812e2a06e77ba15d19eaf2344ebe7861 to your computer and use it in GitHub Desktop.
function getWord(text: string, word: number) {
if (word < 1) throw new Error('word must be no less than 1');
const wordIndex = word - 1;
// https://regex101.com/r/1zDG8a/2
const words = text.toLowerCase().match(/\w+(?:'\w+)*/g);
if (words === null) {
throw new Error('Please provide some text');
}
if (wordIndex >= words.length) {
throw new Error(`Text only has ${words.length} words`);
}
return words[wordIndex];
}
console.log(getWord('This is a test.', 2));
{
"compilerOptions": {
"target": "ES2015",
"noEmitOnError": true,
"strict": true
},
"files": ["./index.ts"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment