查找字符串中的字母距离-JavaScript
我们需要编写一个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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短