你可以使用正则表达式来获取指定字符串后第一个数字或字母的下标。下面是一个例子:

function getIndexAfterString(str, target) {
  const regex = new RegExp(target + '[0-9a-zA-Z]');
  const match = str.match(regex);
  
  if (match) {
    return match.index + target.length;
  }
  
  return -1;
}

// 示例用法
const input = 'Hello, world! The answer is 42.';
const target = 'answer';
const index = getIndexAfterString(input, target);

console.log(index); // 输出 19

在上面的代码中,getIndexAfterString函数接受两个参数:字符串str和目标字符串target。它使用正则表达式构建一个匹配target后紧跟一个数字或字母的模式。然后,它使用match方法在str中找到第一个满足该模式的子串。如果找到了匹配的子串,它返回该子串的起始下标加上target的长度,这就是指定字符串后第一个数字或字母的下标。如果没有找到匹配的子串,它返回-1。

JavaScript 获取指定字符串后第一个数字或字母的下标

原文地址: https://www.cveoy.top/t/topic/kQKf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录