如何用TypeScript实现获取字符串指定索引后的下一个单词?
如何用TypeScript实现
nextWord方法获取指定索引后的下一个单词? 给定如下字符串:
let myText = `The ball is in the garden`;
需要编写一个nextWord方法,接收该字符串和索引i(示例值为9),返回索引i之后的下一个单词(示例中返回is),即调用nextWord(myText, 9)会得到is。
实现思路与代码
核心逻辑是先跳过索引后的所有空白字符,再收集连续的非空白字符作为目标单词,具体实现如下:
function nextWord(text: string, index: number): string | undefined { let currentIndex = index + 1; const textLength = text.length; // 跳过索引后的所有空白字符(空格、换行、制表符等) while (currentIndex < textLength && /\s/.test(text[currentIndex])) { currentIndex++; } // 若已到字符串末尾,无单词可返回 if (currentIndex >= textLength) { return undefined; } // 记录单词起始位置,开始收集非空白字符 const wordStart = currentIndex; while (currentIndex < textLength && !/\s/.test(text[currentIndex])) { currentIndex++; } // 截取并返回目标单词 return text.slice(wordStart, currentIndex); } // 测试示例 let myText = `The ball is in the garden`; console.log(nextWord(myText, 9)); // 输出 "is"
代码说明
- 用
/\s/.test()匹配所有空白字符,兼容多行、缩进等复杂格式场景 - 分两步遍历:先跳过空白找到单词起点,再收集到单词终点,确保只返回有效单词
- 当索引后无单词时返回
undefined,避免返回空字符串这类无意义结果
内容的提问来源于stack exchange,提问作者Abdelghani
相关产品推荐
相关产品推荐

