Skip to content

Instantly share code, notes, and snippets.

@devbanana
Last active Sep 23, 2021
Embed
What would you like to do?
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