在字符串JavaScript中查找空格数


我们需要编写一个 JavaScript 函数,该函数接受一个包含空格的字符串。该函数应简单地计算该字符串中存在的空格数。

例如 -

如果输入字符串是 -

const str = 'this is a string';

那么输出应该是 -

const output = 4;

示例

const str = 'this is a string';
const countSpaces = (str = '') => {
   let count = 0;
   for(let i = 0;
   i < str.length; i++){
      const el = str[i];
      if(el !== ' '){
         continue; };
         count++; };
      return count;
};
console.log(countSpaces(str));

输出

这将生成以下输出 -

4

更新于:2020 年 11 月 25 日

1000+ 次浏览

开启你的职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.