破坏 JavaScript 中的驼峰式语法


问题

我们需要编写一个 JavaScript 函数,该函数将一个 camelCase 字符串 str 作为第一个且唯一的参数输入。

我们的函数应构建并返回一个新的字符串,该字符串使用单词之间的空格拆分输入字符串。

例如,如果对该函数的输入为 -

输入

const str = 'thisIsACamelCasedString';

输出

const output = 'this Is A Camel Cased String';

示例

以下为代码 -

 实时演示

const str = 'thisIsACamelCasedString';
const breakCamelCase = (str = '') => {
   const isUpper = (char = '') => char.toLowerCase() !==
char.toUpperCase() && char === char.toUpperCase();
   let res = '';
   const { length: len } = str;
   for(let i = 0; i < len; i++){
      const el = str[i];
      if(isUpper(el) && i !== 0){
         res += ` ${el}`;
         continue;
      };
      res += el;
   };
   return res;
};
console.log(breakCamelCase(str));

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

输出

this Is A Camel Cased String

更新时间:04-22-2021

189 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告