Breaking camelCase syntax in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a camelCase string, str as the first and the only argument.

Our function should construct and return a new string that splits the input string using a space between words.

For example, if the input to the function is −

Input

const str = 'thisIsACamelCasedString';

Output

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

Example

Following is the code −

 Live Demo

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));

Output

this Is A Camel Cased String
raja
Published on 22-Apr-2021 13:12:54
Advertisements