计数相邻的成对字在JavaScript

问题

我们需要编写JavaScript函数,它在一个字符串str表示句子作为唯一的参数。

我们的函数应该计数并返回相邻的一对相同的词存在于字符串str。我们的函数应该检查的话忽略他们的情况下,这意味着“它”和“这是应该算作相同。

例如,如果函数的输入是 -

输入

const str = 'This this is a a sample string';

输出

const output = 2;

输出说明

因为重复字是“这个”和“A”。

示例

以下是代码 -

const str = 'This this is a a sample string';
const countIdentical = (str = '') => {
   const arr = str.split(' ');
   let count = 0;
   for(let i = 0; i <arr.length- 1; i++){
      const curr = arr[i];
      const next = arr[i + 1];
      if(curr.toLowerCase() === next.toLowerCase()){
         count++;
      };
   };
   return count;
};
console.log(countIdentical(str));
输出结果
2