How to match the first word after an expression in a string using RegEx with TypeScript

1 Answer

0 votes
function findNextWord(text: string, expression: string): void {
    const escapedExpression: string = expression.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    const pattern: RegExp = new RegExp(`${escapedExpression}\\s+(\\w+)`);
    const match: RegExpExecArray | null = pattern.exec(text);
    
    if (match) {
        console.log(`The first word after '${expression}' is: ${match[1]}`);
    } else {
        console.log('No match found!');
    }
}

const text: string = 'The quick brown fox jumps over the lazy dog.';
const expression: string = 'fox';

findNextWord(text, expression);



   
/*
run:

"The first word after 'fox' is: jumps" 
   
*/

 



answered Jun 15, 2025 by avibootz
...