JavaScript查找字符串中的字母距离

2023年11月25日11:56:20

我们需要编写一个JavaScript函数,该函数接受一个字符串作为第一个参数以及两个单元素字符串。函数应返回字符串中作为第一个参数的那些单个字母between之间的距离。

例如-

如果三个字符串是-

const str = 'Disaster management';
const a = 'i', b = 't';

然后输出应该是4,因为“ i”和“ t”之间的距离是4

示例

以下是代码-

const str = 'Disaster management';
const a = 'i', b = 't';
const distanceBetween = (str, a, b) => {
   const aIndex = str.indexOf(a);
   const bIndex = str.indexOf(b);
   if(aIndex === -1 || b === -1){
      return false;
   };
   return Math.abs(aIndex - bIndex);
};
console.log(distanceBetween(str, a, b));

输出结果

以下是控制台中的输出-

4

  • 更新时间:2023年11月25日11:56:20 ,共 501 字。