JavaScript如何实现从字符串中提取关键字entry后的数字
JavaScript 实现关键字后数字检索方案
直接通过正则匹配即可实现需求,无需引入额外依赖:
核心实现函数
/** * 提取文本中指定关键字后方的数字 * @param {string} text 待检索的原文本 * @param {string} keyword 要定位的关键字 * @returns {number|null} 匹配到的数字,未匹配到时返回null */ function getNumAfterKeyword(text, keyword) { // 正则逻辑:匹配关键字 + 任意非数字字符 + 捕获连续数字 const matchRes = text.match(new RegExp(`${keyword}\\D*(\\d+)`)); return matchRes ? Number(matchRes[1]) : null; }
测试用例
const demoText = "this is a signal , entry : 2430 and side is short"; const targetNum = getNumAfterKeyword(demoText, 'entry'); console.log(targetNum); // 输出 2430
适配扩展
- 如需支持关键字大小写不敏感匹配,可给正则添加
i修饰符:new RegExp(${keyword}\D*(\d+), 'i') - 如需匹配所有符合规则的数字,可添加
g修饰符后循环遍历匹配结果即可
内容的提问来源于stack exchange,提问作者dumpAndDie
相关产品推荐
相关产品推荐

